LEETCODE算法:56. Merge Intervals

题目

Given a collection of intervals, merge all overlapping intervals.

Example 1:

Input: [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. Example 2:

Input: [[1,4],[4,5]] Output: [[1,5]] Explanation: Intervals [1,4] and [4,5] are considered overlapping. NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//排序合并
class Solution {
static bool cmp(vector<int> &a,vector<int> &b)
{
if(a[0]!=b[0]) return a[0]<b[0];
else return a[1]<b[1];
}
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> res;
if(intervals.size()==0) return res;
sort(intervals.begin(),intervals.end(),cmp);
for(int i=0;i<intervals.size();i++)
{
if(i==0||intervals[i][0]>res.back()[1])
{
res.push_back(vector<int>{intervals[i][0],intervals[i][1]});
}else{
res.back()[1]=max(res.back()[1],intervals[i][1]);
}
}
return res;
}

};