-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathMerge Overlapping Intervals
More file actions
41 lines (33 loc) · 965 Bytes
/
Merge Overlapping Intervals
File metadata and controls
41 lines (33 loc) · 965 Bytes
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
35
36
37
38
39
40
41
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].
Make sure the returned intervals are sorted.
*******************************************************************************************************
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
int comp(Interval a , Interval b){
return a.start<b.start;
}
vector<Interval> Solution::merge(vector<Interval> &A) {
vector<Interval> res;
if(A.size() == 0) return res;
sort(A.begin(),A.end(),comp);
res.push_back(A[0]);
for(int i=1 ; i<A.size() ; i++){
if(res.back().end >= A[i].start){
res.back().end = max(res.back().end,A[i].end);
}
else{
res.push_back(A[i]);
}
}
return res;
}