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

问题:给定一个区间数组,插入一个新的区间元素。区间数组已经按照 区间开始值升序排序。

思路:

1. 找到左边第一个 intervals[i].end >= newInterval.start 的元素。

2. 若 intervals[i].start > newInterval.end,则在 i 位置插入 newInterval ,程序结束。否则,将后续所有 intervals[j].start <= newInterval.end (i <= j)的元素合并到 i 位置,intervals[i].start 取涉及合并的最小值, intervals[i].end 取涉及合并的最大值。

3. 将 i 后面没有涉及合并的元素往前移动,移动至紧跟 i 元素。

这道题的思路不难也比较直观,时间效率为 O(n),只是需要处理的边界情况比较多。例如有首部插入区间数组、尾部插入区间数组、以及完全覆盖的区间数组情况。

 1 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
 2     
 3     if (intervals.size() == 0) {
 4         intervals.push_back(newInterval);
 5         return intervals;
 6     }
 7     
 8     if (newInterval.end < intervals[0].start) {
 9         intervals.insert(intervals.begin(), newInterval);
10         return intervals;
11     }
12     
13     if (newInterval.start > intervals[intervals.size()-1].end) {
14         intervals.push_back(newInterval);
15         return intervals;
16     }
17     
18     if (newInterval.start <= intervals[0].start && intervals[intervals.size()-1].end <= newInterval.end) {
19         intervals.clear();
20         intervals.push_back(newInterval);
21         return intervals;
22     }
23     
24     
25     int len = (int)intervals.size();
26     int i = 0;
27     for ( ; i < intervals.size(); i++) {
28         if (intervals[i].end >= newInterval.start) {
29             break;
30         }
31     }
32     int theIdx = i;
33     
34     if (intervals[theIdx].start > newInterval.end) {
35         vector<Interval>::iterator nth = intervals.begin() + theIdx;
36         intervals.insert(nth, newInterval);
37         return intervals;
38     }else{
39         intervals[theIdx].start = min( intervals[theIdx].start, newInterval.start);
40 
41     }
42 
43     while (i < intervals.size() && intervals[i].start <= newInterval.end) {
44         intervals[theIdx].end = max(intervals[i].end, newInterval.end);
45         i++;
46     }
47         
48     int j = theIdx + 1;
49     
50     while (i < intervals.size()) {
51         intervals[j] = intervals[i];
52         i++;
53         j++;
54     }
55     
56     while (j < len) {
57         intervals.pop_back();
58         j++;
59     }
60     
61     return intervals;
62 }

 

posted @ 2015-12-29 20:45  TonyYPZhang  阅读(325)  评论(0编辑  收藏  举报