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].
To see this topic, I first produced a question is: is the original interval vector modified, or re-create a new and then return? Although this problem will not lead to the fundamental difference of the algorithm, but in the implementation will bring a relatively large difference.
My idea about this is that because the parameters passed in are reference types, I don't think that the original vector should be modified and a new one should be returned.
My solution is to set two flags Foundstart and Foundend, respectively, to identify whether the start and end points of the new interval are found, purely based on the interval relationship, so it is relatively cumbersome to implement:
vector<interval> Insert (vector<interval> &intervals, Interval newinterval) {vector<interval> Mergedintervals; int start = 0, end = 0; BOOL Foundstart = False, Foundend = false; for (auto interval:intervals) {if (!foundstart) {if (Interval.end < Newinterval.start) Mergedinte Rvals.push_back (interval); else if (Interval.start > Newinterval.end) {mergedintervals.push_back (newinterval); Mergedintervals.push_back (interval); Foundstart = true; Foundend = true; } else {start = Interval.start < Newinterval.start? interval.start:newInterval.start; Foundstart = true; if (newinterval.end <= interval.end) {mergedintervals.push_back (interval (start, interval.end)); Foundend = true; } else end = Newinterval.end; } } else if (!foundend) {if (Interval.start > End) {mergedintervals.push_back (I Nterval (start, end)); Mergedintervals.push_back (interval); Foundend = true; } else if (end < Interval.end) {Mergedintervals.push_back (interval (start, interval.end)); Foundend = true; }} else Mergedintervals.push_back (interval); } if (!foundstart) mergedintervals.push_back (newinterval); else if (!foundend) Mergedintervals.push_back (Interval (Start, end)); return mergedintervals;}
There is a better solution on the discuss.
Leetcode[array]: Insert Interval