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]
.
Analyse: First sort, then merge.
Notice the static function!
Runtime: 592ms
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 */ 10 class Solution { 11 public: 12 static bool compare(Interval &interval1, Interval &interval2){ 13 return interval1.start < interval2.start; 14 } 15 vector<Interval> merge(vector<Interval>& intervals) { 16 vector<Interval> result; 17 if(intervals.size() == 0) return result; 18 if(intervals.size() == 1) return intervals; 19 20 sort(intervals.begin(), intervals.end(), Solution::compare); 21 Interval inter(intervals[0].start, intervals[0].end); 22 for(int i = 1; i < intervals.size(); i++){ 23 if(inter.end < intervals[i].start){ 24 result.push_back(inter); 25 inter.start = intervals[i].start; 26 inter.end = intervals[i].end; 27 } 28 else{ 29 inter.start = min(inter.start, intervals[i].start); 30 inter.end = max(inter.end, intervals[i].end); 31 } 32 } 33 result.push_back(inter); 34 return result; 35 } 36 };
Runtime: 596ms.
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 */ 10 class Solution { 11 public: 12 vector<Interval> merge(vector<Interval>& intervals) { 13 vector<Interval> result; 14 if(intervals.empty()) return result; 15 16 sort(intervals.begin(), intervals.end(), comp); 17 result.push_back(intervals[0]); 18 if(intervals.size() == 1) return result; 19 20 for(int i = 1; i < intervals.size(); i++){ 21 if(intervals[i].start > result[result.size() - 1].end) 22 result.push_back(intervals[i]); 23 else{ 24 intervals[i].start = min(intervals[i].start, result[result.size() - 1].start); 25 intervals[i].end = max(intervals[i].end, result[result.size() - 1].end); 26 result.pop_back(); 27 result.push_back(intervals[i]); 28 } 29 } 30 return result; 31 } 32 33 static bool comp(Interval int1, Interval int2){ 34 return int1.start < int2.start; 35 } 36 };