One Day Together Leetcode series (i) Title
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 [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 was because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
(ii) Problem solving
Related topics: "One day together Leetcode" #56. Merge intervals
/ * Main problem solving ideas: 1, when Intervals[i].end<newinterval.start, do not need to merge, direct i++2, when found the first meet intervals[i].end> When Newinterval.start, determine the start value of the merged interval 3, when the last one is found to meet the intervals[i].start> When Newinterval.end, determine the end value of the merged interval * //** * Definition for an interval. * struct INTERVAL {* int start; * int end; * Interval (): Start (0), end (0) {} * Interval (int s, int e): Start (s), End (e) {} *}; */classSolution { Public: vector<Interval>Insert vector<Interval>& intervals, Interval newinterval) { vector<Interval>Retif(intervals.size () = =0){//Special casesRet.push_back (NewInterval);returnRet }inti =0; Interval tmp; while(I<intervals.size () &&intervals[i].end<newinterval.start) {//Press the interval directly into the RET without needing to mergeRet.push_back (Intervals[i]); i++; } ? ?//found the first I value satisfying the Intervals[i].end>newinterval.start? ?//It is important to note that when NewInterval is larger than the value inside the vectorTmp.start = min (i==intervals.size () newinterval.start:intervals[i].start,newinterval.start); Tmp.end = Newinterval.end; while(I<intervals.size () &&intervals[i].start<=newinterval.end) {tmp.end = max (intervals[i].end,newinterval.end);//Find the merged end valuei++; } ret.push_back (TMP); while(I<intervals.size ()) {//Press the remaining interval into the RETRet.push_back (Intervals[i]); i++; }returnRet }};
"One Day together Leetcode" #57. Insert Interval