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]
.
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { auto iter = intervals.begin(); while (iter != intervals.end() && iter->end < newInterval.start) ++iter; if (iter != intervals.end()) { auto iend = iter; while (iend != intervals.end() && newInterval.end >= iend->start) ++iend; if (iter != iend) { newInterval.start = min(newInterval.start, iter->start); --iend; newInterval.end = max(newInterval.end, iend->end); ++iend; iter = intervals.erase(iter, iend); } } intervals.insert(iter, newInterval); return intervals; } };
该算法在leetcode上实际执行时间为16ms。
基本思路为,
在数组中找到和待插入的区间有重叠的所以区间 [iter, iend), 注,左闭右开。
若存在,合并区间信息到待插入区间。并删除原有的重叠区间。
若不存在,则直接插入。
所要注意的事项为,用范围删除,即先找到范围,再整体删除。
如果找到一个区间,就删除一个。 在运行时间上将不能被AC。
时间: 2024-10-26 14:54:45