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 private: 12 static bool cmp(const Interval& ina,const Interval& inb){ 13 return ina.start < inb.start; 14 } 15 16 public: 17 vector<Interval> merge(vector<Interval>& intervals) { 18 19 vector<Interval> result; 20 int count = intervals.size(); 21 if(count <= 1){ 22 return intervals; 23 } 24 //先按start排序 25 sort(intervals.begin(),intervals.end(),cmp); 26 // 合并 三种情况 27 result.push_back(intervals[0]); 28 29 30 for(int i = 1;i < count;i++){ 31 Interval preIn = result.back(); 32 Interval curIn = intervals[i]; 33 if(curIn.start <= preIn.end && curIn.end > preIn.end){ 34 preIn.end = curIn.end; 35 result.pop_back(); 36 result.push_back(preIn); 37 } 38 else if(curIn.start > preIn.end){ 39 result.push_back(curIn); 40 } 41 } 42 return result; 43 44 } 45 };