Leetcode 56. Merge Intervals
56. Merge Intervals
- Total Accepted: 75204
- Total Submissions: 285007
- Difficulty: Hard
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]
.
思路:先根据区间左边界大小升序排序区间,然后向右合并。注意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 public: 12 static bool comp(Interval a,Interval b){ 13 return a.start<b.start; 14 } 15 vector<Interval> merge(vector<Interval>& intervals) { 16 vector<Interval> res; 17 if(!intervals.size()) return res; 18 sort(intervals.begin(),intervals.end(),comp); 19 res.push_back(intervals[0]); 20 for(int i=1;i<intervals.size();i++){ 21 if(intervals[i].start>res.back().end){ 22 res.push_back(intervals[i]); 23 } 24 else{ 25 res.back().end=max(intervals[i].end,res.back().end); 26 } 27 } 28 return res; 29 } 30 };
sort排序也可以这样写:
1 class Solution { 2 public: 3 vector<Interval> merge(vector<Interval>& intervals) { 4 vector<Interval> res; 5 if(!intervals.size()) return res; 6 sort(intervals.begin(),intervals.end(),[](Interval a, Interval b){return a.start < b.start;}); 7 res.push_back(intervals[0]); 8 for(int i=1;i<intervals.size();i++){ 9 if(intervals[i].start>res.back().end){ 10 res.push_back(intervals[i]); 11 } 12 else{ 13 res.back().end=max(intervals[i].end,res.back().end); 14 } 15 } 16 return res; 17 } 18 };