-
Notifications
You must be signed in to change notification settings - Fork 2
/
56. Merge Intervals.cpp
34 lines (29 loc) · 1016 Bytes
/
56. Merge Intervals.cpp
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
26
27
28
29
30
31
32
33
34
class Solution {
public:
static bool comparator( vector<int>& a, vector<int>& b ){
return a[0] < b[0];
}
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> res;
if( intervals.empty() ) return res;
if( intervals.size() == 1 ) {
res.push_back( intervals[0]);
return res;
}
sort( intervals.begin(), intervals.end(), comparator );
//Push the first interval into the result
res.push_back( intervals[0] );
int i = 1;
while( i < intervals.size() ){
vector<int>& last = res.back();
//Check for overlapping boundaries in the intervals and merge them suitably
if( last[1] < intervals[i][0] ) {
res.push_back( intervals[i] );
}else {
last[1] = max( last[1], intervals[i][1] );
}
i++;
}
return res;
}
};