[LeetCode] 56. Merge Intervals(vector sort)
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 { 12 public: 13 static bool cmp(Interval &a,Interval &b) 14 { 15 return a.start < b.start; 16 } 17 vector<Interval> merge(vector<Interval>& intervals) 18 { 19 if(intervals.empty()) return vector<Interval> {}; 20 sort(intervals.begin(),intervals.end(),cmp); 21 vector<Interval> res; 22 res.push_back(intervals[0]); 23 for(int i = 1; i < intervals.size(); i ++) 24 { 25 if(intervals[i].start > res.back().end) 26 res.push_back(intervals[i]); 27 else 28 res.back().end = max(res.back().end, intervals[i].end); 29 } 30 return res; 31 } 32 };