Insert Interval
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]
.
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 classSolution { One Public: Avector<interval> Insert (vector<interval> &intervals, Interval newinterval) { - - intn=intervals.size (); theVector<interval>result; - - if(n==0) - { + Result.push_back (newinterval); - returnresult; + } A at intstart=Newinterval.start; - intEnd=Newinterval.end; - - - BOOLisfindstart=false; - BOOLIsfindend=false; in BOOLAddcur=true; - to for(intI=0; i<n;i++) + { -Addcur=true; the * if(!Isfindstart) $ {Panax Notoginseng //does not intersect with the current interval and is in front of start - if(start>intervals[i].end) the { + //need to add current element AAddcur=true; the //when the current element is the last element, it is assumed that start has found the + if(i==n-1) isfindstart=true; - } $ Else $ { - //intersect with current interval or start less than current interval - thestart=min (start,intervals[i].start); - //you don't have to start looking for the next.Wuyiisfindstart=true; the - //if start and end do not have a cross with other interval Wu if(End<intervals[i].start) addcur=true; - ElseAddcur=false; About } $ } - - - if(!isfindend) A { + //need to continue looking for end the if(end>intervals[i].end) - { $ the if(start<=intervals[i].end) addcur=false; the the if(i==n-1) the { -Isfindend=true; in the if(addcur) result.push_back (Intervals[i]); the Result.push_back (Interval (start,end)); About the Continue; the } the } + Else - { the //end is less than the current interval and the end is found at this timeBayiEnd=end>=intervals[i].start?Intervals[i].end:end; the the //found the end -Isfindend=true; - if(End>=intervals[i].start) addcur=false; the the Result.push_back (Interval (start,end)); the if(addcur) result.push_back (Intervals[i]); the - Continue; the } the } the 94 if(addcur) result.push_back (Intervals[i]); the } the returnresult; the }98};
"Leetcode" Insert Interval