标签:
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:
Given intervals [1,3],[6,9]
, insert and merge [2,5]
in as [1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge [4,9]
in as [1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
思路:区间划分。先找到新区间的左边界,再找到新区间的右边界。画图会更加清晰。
左边界:不满足intervals[i].end<newInterval.start意味着intervals[i-1].end<newInterval.start<=intervals[i].end。
右边界:满足intervals[j].start<newInterval.end时,不断合并区间,将intervals[j]和newInterval合并为新的newInterval,再尝试和intervals[j+1]合并,直到不能合并。因为intervals[j]和intervals[j+1]是区间独立的,所以intervals[j]被合并不会影响intervals[j+1]。
代码:
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 int i,j; 14 vector<Interval> res; 15 for(i=0;i<intervals.size()&&intervals[i].end<newInterval.start;i++){//i 16 res.push_back(intervals[i]); 17 } 18 for(j=i;j<intervals.size()&&intervals[j].start<=newInterval.end;j++){ 19 newInterval=Interval(min(intervals[j].start,newInterval.start),max(intervals[j].end,newInterval.end)); 20 } 21 res.push_back(newInterval); 22 for(;j<intervals.size();j++){ 23 res.push_back(intervals[j]); 24 } 25 return res; 26 } 27 };
标签:
原文地址:http://www.cnblogs.com/Deribs4/p/5735405.html