标签:
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]
.
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(),cmp); 17 18 int start=intervals[0].start; 19 int end=intervals[0].end; 20 21 for(int i=1;i<intervals.size();i++) 22 { 23 if(intervals[i].start<=end) 24 { 25 //注意[1,4],[2,3]的情况 26 end=end<intervals[i].end?intervals[i].end:end; 27 } 28 else 29 { 30 result.push_back(Interval(start,end)); 31 start=intervals[i].start; 32 end=intervals[i].end; 33 } 34 } 35 36 result.push_back(Interval(start,end)); 37 return result; 38 } 39 40 static int cmp(const Interval &a,const Interval &b) 41 { 42 if(a.start<b.start) return 1; 43 else if(a.start>b.start) return 0; 44 else return a.end<b.end; 45 } 46 };
标签:
原文地址:http://www.cnblogs.com/reachteam/p/4209522.html