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] .
/** * Definition for an interval. * struct Interval {* int start; * int end; * Interval (): Start (0), end (0) {} * Interval (int s, int e): Start (s), End (e) {}}; */class Solution {public: vector<interval> merge (vector<interval> &intervals) { if ( Intervals.size () <= 1) return intervals; Sort (Intervals.begin (), Intervals.end (), [] (const Interval &a, const Interval &b) {return A.start < B.start;}) ; size_t j = 0; for (size_t i = j+1; I<intervals.size (); i++) { if (intervals[j].end >= intervals[i].start) Intervals[j] . end = Max (Intervals[j].end, intervals[i].end); else intervals[++j] = intervals[i]; } Intervals.erase (Intervals.begin () +j+1, Intervals.end ()); return intervals;} ;
The execution time of the algorithm on Leetcode is 20ms.
Basic ideas:
1. Sort by using a custom comparison function to achieve ascending by start.
2. Using Remove-duplicates-from-sorted-array's ideas to merge
Merge intervals--Leetcode