首页 > 代码库 > Leetcode | Insert Interval

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

思路就是找到要merge的n个区间,然后把这几个区间删掉,再把新的区间插进去。

s初始化为-1,s+1就是插入的位置。s记录的是要merge的区间的前一个区间,所以插入位置就是s+1。

i就是要merge的区间的后一个区间。

如果merge错的话,可能会出现Output Limit Exceeded。

56ms。

 1 class Solution {
 2 public:
 3     vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
 4         int s = -1, i = 0;
 5         for (; i < intervals.size(); ++i) {
 6             if (newInterval.end < intervals[i].start) {
 7                 break;
 8             }
 9             if (newInterval.start > intervals[i].end) {
10                 s = i;
11                 continue;
12             }
13             
14             if (intervals[i].start < newInterval.start) newInterval.start = intervals[i].start;
15             if (intervals[i].end > newInterval.end) newInterval.end = intervals[i].end;
16         }
17         
18         if (i - s >= 2) intervals.erase(intervals.begin() + s + 1, intervals.begin() + i);
19         intervals.insert(intervals.begin() + s + 1, newInterval);
20         return intervals;
21     }
22 };