题目:

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从头到尾遍历,用new interval与相应的interval[i]对比,如果整个new interval都在interval[i]的左边,就把new interval存到result里,然后把剩下的所有interval都存起来即可,如果new interval在interval[i]的右边,则存起来interval[i],然后继续遍历; 如果new interval 和 interval[i]有overlap, 则将两者进行合并,然后继续遍历。

 

代码: 

 1 class Solution {
 2 public:
 3     vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<Interval> result;
 7         
 8         for (int i = 0; i<intervals.size(); i++){
 9             
10             if (intervals[i].end < newInterval.start)
11                result.push_back(intervals[i]);
12             else if (intervals[i].start>newInterval.end){
13                 
14                 result.push_back(newInterval);
15                 while (i<intervals.size()){
16                     
17                     result.push_back(intervals[i]);
18                     i++;
19                 }
20             }
21             
22             else{
23                 
24                 newInterval.start = min(intervals[i].start, newInterval.start);
25                 newInterval.end = max(intervals[i].end, newInterval.end);
26                 
27             }
28         }
29         
30         if(0 == result.size() || result.back().end < newInterval.start)  
31             result.push_back(newInterval);  
32         
33         return result;
34     }
35 };

 

posted on 2013-05-11 04:56  tanghulu321  阅读(147)  评论(0编辑  收藏  举报