Leetcode 57. Insert Interval
Problem:
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]
.
Solution:
经典问题,两种做法。第一种,根据intervals的开始时间将newInterval插入到合适的位置,然后对intervals进行合并。第二种,找到完全在newInterval左侧的interval放到数组left中,找到完全在newInterva右侧的interval放到数组right中,对于有重合的interval向两头拓展start和end,最后将left+{start,end}+right合并为结果数组
Code:
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { 13 auto iter = intervals.begin(); 14 while(iter != intervals.end() && iter->start < newInterval.start) 15 iter++; 16 intervals.insert(iter,newInterval); 17 vector<Interval> result; 18 for(int i = 0;i != intervals.size();++i){ 19 if(result.empty() || intervals[i].start > result.back().end) 20 result.push_back(intervals[i]); 21 else{ 22 result.back().end = max(result.back().end,intervals[i].end); 23 } 24 } 25 return result; 26 } 27 };
1 /** 2 * Definition for an interval. 3 * struct Interval { 4 * int start; 5 * int end; 6 * Interval() : start(0), end(0) {} 7 * Interval(int s, int e) : start(s), end(e) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) { 13 vector<Interval> left,right; 14 vector<Interval> result; 15 int start = newInterval.start; 16 int end = newInterval.end; 17 for(int i = 0;i != intervals.size();++i){ 18 if(end < intervals[i].start) 19 right.push_back(intervals[i]); 20 else if(start > intervals[i].end) 21 left.push_back(intervals[i]); 22 else{ 23 start = min(start,intervals[i].start); 24 end = max(end,intervals[i].end); 25 } 26 } 27 for(int i = 0;i != left.size();++i) 28 result.push_back(left[i]); 29 Interval interval(start,end); 30 result.push_back(interval); 31 for(int i = 0;i != right.size();++i) 32 result.push_back(right[i]); 33 return result; 34 } 35 };