LeetCode | 57. Insert Interval

 

题目:

Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

You may assume that the intervals were initially sorted according to their start times.

Example 1:

Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
Output: [[1,5],[6,9]]

Example 2:

Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
Output: [[1,2],[3,10],[12,16]]
Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].

NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

 

代码:

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> merged;
		if(intervals.size() < 1)
			return merged;
		merged.push_back(intervals[0]);
		int idx = 0;
		for(int i = 1; i<intervals.size(); i++)
		{
			if(intervals[i].start >= merged[idx].start && intervals[i].start <= merged[idx].end)
			{
				merged[idx].start = min(merged[idx].start, intervals[i].start);
				merged[idx].end = max(merged[idx].end, intervals[i].end);
			}
			else
			{
				merged.push_back(intervals[i]);
				idx++;
			}
		}
		return merged;
    }
    vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
        if(intervals.size() < 1)
            intervals.push_back(newInterval);
        else
        {
            int insertFlag = 1;
            if(newInterval.start < intervals[0].start || (newInterval.start == intervals[0].start && newInterval.end < intervals[0].end))
            {    
                intervals.insert(intervals.begin(), newInterval);
                insertFlag = 0;
            }
            for(int i = 1; i<intervals.size() && insertFlag; i++)
            {
                if(newInterval.start < intervals[i].start || (newInterval.start == intervals[i].start && newInterval.end <= intervals[i].end))
                {
                    intervals.insert(intervals.begin()+i, newInterval);
                    insertFlag = 0;
                }
            }
            if(insertFlag)
            {
                intervals.push_back(newInterval);
            }
        }
        vector<Interval> mergeIntervals = merge(intervals);
        return mergeIntervals;
    }
};

 

 

 

 

 

 

上一篇:P4747 [CERC2017]Intrinsic Interval


下一篇:LeetCode | 56. Merge Intervals