LeetCode, leetcodeoj
Link: Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18], return [1,6],[8,10],[15,18].
The requirement for this question is to merge a given set of intervals that overlap.
To merge an interval, first locate the adjacent interval and check whether there is overlap. If yes, merge the interval.
Therefore, first consider sorting the array. When sorting, you only need to sort by the start time of the interval. Then, the array is traversed. the end time of the Current interval is no less than the start time of the Current interval. This indicates that there are overlaps and needs to be merged. When merging, the end time of the new interval is equal to the maximum of the end time of the two intervals.
During implementation, the first interval is first placed in the new array, and then traversed from the second one. If there is overlap, the end time of the last element in the new array is changed; if there is no overlap, add it to the new array.
Time Complexity: O (nlogn)
Space complexity: O (n)
1 bool cmp(Interval i1, Interval i2) 2 { 3 return i1.start < i2.start; 4 } 5 6 class Solution 7 { 8 public: 9 vector<Interval> merge(vector<Interval> &intervals)10 {11 vector<Interval> vi;12 13 if(intervals.size() == 0)14 return vi;15 16 sort(intervals.begin(), intervals.end(), cmp);17 18 vi.push_back(intervals[0]);19 for(int i = 1; i < intervals.size(); ++ i)20 {21 if(vi[vi.size() - 1].end >= intervals[i].start)22 vi[vi.size() - 1].end = max(vi[vi.size() - 1].end, intervals[i].end);23 else24 vi.push_back(intervals[i]);25 }26 return vi;27 }28 };
Reprinted please note the Source: LeetCode --- 56. Merge Intervals