[LeetCode] 57. Insert Interval 解决思路

时间:2022-04-26 04:01:53

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),只是需要处理的边界情况比较多。例如有首部插入区间数组、尾部插入区间数组、以及完全覆盖的区间数组情况。

 vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {

     if (intervals.size() == ) {
intervals.push_back(newInterval);
return intervals;
} if (newInterval.end < intervals[].start) {
intervals.insert(intervals.begin(), newInterval);
return intervals;
} if (newInterval.start > intervals[intervals.size()-].end) {
intervals.push_back(newInterval);
return intervals;
} if (newInterval.start <= intervals[].start && intervals[intervals.size()-].end <= newInterval.end) {
intervals.clear();
intervals.push_back(newInterval);
return intervals;
} int len = (int)intervals.size();
int i = ;
for ( ; i < intervals.size(); i++) {
if (intervals[i].end >= newInterval.start) {
break;
}
}
int theIdx = i; if (intervals[theIdx].start > newInterval.end) {
vector<Interval>::iterator nth = intervals.begin() + theIdx;
intervals.insert(nth, newInterval);
return intervals;
}else{
intervals[theIdx].start = min( intervals[theIdx].start, newInterval.start); } while (i < intervals.size() && intervals[i].start <= newInterval.end) {
intervals[theIdx].end = max(intervals[i].end, newInterval.end);
i++;
} int j = theIdx + ; while (i < intervals.size()) {
intervals[j] = intervals[i];
i++;
j++;
} while (j < len) {
intervals.pop_back();
j++;
} return intervals;
}