Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
Assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge in as [2,5]
[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge in as [4,9]
[1,2],[3,10],[12,16]
.
This is because, the new interval [4,9]
overlaps with [3,5],[6,7],[8,10]
.
First put the interval you want to insert to the last, then sort it, and then it's exactly the same as the title.
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 */Ten One BOOLcmpConstInterval &a,ConstInterval &b) { A returnA.start <B.start; - } - the classSolution { - Public: -vector<interval> Insert (vector<interval> &intervals, Interval newinterval) { - intpos =0, cnt =0; + Intervals.push_back (newinterval); - sort (Intervals.begin (), Intervals.end (), CMP); + for(inti =1; I < intervals.size (); ++i) { A if(Intervals[pos].end >=Intervals[i].start) { at++CNT; - if(Intervals[pos].end <intervals[i].end) { -Intervals[pos].end =Intervals[i].end; - } -}Else { -++Pos; inIntervals[pos].start =Intervals[i].start; -Intervals[pos].end =Intervals[i].end; to } + } -Intervals.resize (Intervals.size ()-CNT); the returnintervals; * } $};
[Leetcode] Insert Interval