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:
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].

思路:

对于有n个区间的vector,分成了2*n+1个部分。根据这个性质,对于一个新的interval,先判断它的左右点都在哪一部分,然后将被覆盖的部分删除即可。

下面代码中findIndex负责找到某个int值所在的区域。

代码:

 1     int findIndex(vector<Interval> &intervals, int val){
 2         int n = intervals.size();
 3         if(val < intervals[0].start) 
 4             return 0;
 5         if(val > intervals[n-1].end)
 6             return 2*n;
 7         for(int i = 0; i < n; i++){
 8             if(val >= intervals[i].start && val <= intervals[i].end)
 9                 return 2*i+1;
10             if(i < n-1 && val > intervals[i].end && val < intervals[i+1].start)
11                 return 2*i+2;
12             if(i > 0 && val > intervals[i-1].end && val < intervals[i].start)
13                 return 2*i;
14         }
15     }
16     vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
17         // IMPORTANT: Please reset any member data you declared, as
18         // the same Solution instance will be reused for each test case.
19         if(intervals.size() == 0){
20             intervals.push_back(newInterval);
21             return intervals;
22         }
23         int size = intervals.size();
24         int s = findIndex(intervals, newInterval.start), e = findIndex(intervals, newInterval.end);
25         cout<<s<<"-"<<e<<endl;
26         if(s%2 == 1){
27             newInterval.start = intervals[s/2].start;
28         }
29         if(e%2 == 1){
30             newInterval.end = intervals[e/2].end;
31         }
32         if(s == e){
33             if(s%2 != 1)
34                 intervals.insert(intervals.begin()+s/2, newInterval);
35         }
36         else{
37             s /= 2;
38             if(e%2 == 0)
39                 e /= 2;
40             else
41                 e = e/2+1;
42             if(e > size)
43                 e = size;
44             cout<<s<<"-"<<e<<endl;
45             intervals.erase(intervals.begin()+s, intervals.begin()+e);
46             intervals.insert(intervals.begin()+s, newInterval);
47         }
48         return intervals;
49     }  

 

posted on 2013-11-22 21:41  waruzhi  阅读(173)  评论(0编辑  收藏  举报

导航