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.
思路:主要注意所加的项与原数组重叠的部分,不重叠的直接放入目标数组中。 我们把原数组分为:end小于所加项start的部分,这一部分是不重叠的,还有start大于所加项end的部分也是不重叠的,我们看重叠的部分,我们需要的是重叠出start=min(原项start,所加项start),end=max(原项max, 所加项max),这样就可以吧重复的部分除去,得到想要的结果。
/**
* 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) {
vector<Interval>result;
int i = 0;
for (; i < intervals.size(); i++) {
if (intervals[i].end < newInterval.start) {
result.push_back(intervals[i]);
} else {
break;
}
}
result.push_back(newInterval);
for(; i < intervals.size(); i++) {
if (intervals[i].start <= newInterval.end) {
result[result.size() - 1].start = min(result[result.size() - 1].start, intervals[i].start);
result[result.size() - 1].end = max(result[result.size() - 1].end, intervals[i].end);
}
else {
break;
}
}
for (; i < intervals.size(); i++) {
result.push_back(intervals[i]);
}
return result;
}
};