标签:
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 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4718878.html