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 };

 第三次写,用一个新的vector复制,因为vector的删除也是复制,这样还高效一点。

1. 不可能有交集的区间直接复制。

2. 有交集的区间求最终的交集。

3. 剩下的又直接复制。

这样可以不用对空输入进行特殊处理。

 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         vector<Interval> ans;

14         

15         int i = 0;

16         for (; i < intervals.size(); ++i) {

17             if (intervals[i].end < newInterval.start) {

18                 ans.push_back(intervals[i]);

19             } else if (intervals[i].start > newInterval.end) {

20                 break;

21             } else {

22                 if (intervals[i].end > newInterval.end) newInterval.end = intervals[i].end;

23                 if (intervals[i].start < newInterval.start) newInterval.start = intervals[i].start;

24             }

25         }

26         ans.push_back(newInterval);

27         for (;i < intervals.size(); ++i) {

28             ans.push_back(intervals[i]);

29         }

30         

31         return ans;

32     }

33 };

 

你可能感兴趣的:(LeetCode)