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]
.
題目的意思:給定一個非重疊的區間,插入一個新的區間,如果區間與其他區間相交,則必須合併
注意題目有個假設,區間根據start時間進行了排序,所以自己不需要排序
struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} };
解題思路:設給定的區間為intervals,插入的區間為newInterval,只需要將newInterval與intervals相交的區間合併即可,
如果newInterval與intervals沒有相交的區間,則必須將newInterval插入到相應的位置
本題有三種情況
(1)如果intervals[i].end < newInterval.start,說明intervals[i]與newInterval不相交,保留即可
(2)如果intervals[i].start > newInterval.end, 說明intervals[i]與newInterval不相交,將newInterval插入即可,注意這時候其後面的intervals[i],都可以保留,這是由於本身區間是不想交的。
(3) 如果intervals[i].start < newInterval.end,說明區間相交,合併區間,更新newInterval
class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { vector<Interval> res; for(int i = 0 ; i < intervals.size(); ++ i){ if(intervals[i].end < newInterval.start) res.push_back(intervals[i]); else if(intervals[i].start > newInterval.end) { res.push_back(newInterval); newInterval = intervals[i]; }else if(intervals[i].start <= newInterval.end ){ newInterval.start = min(newInterval.start, intervals[i].start); newInterval.end = max(newInterval.end, intervals[i].end); } } res.push_back(newInterval); return res; } };