-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMerge_Intervals.cpp
More file actions
38 lines (36 loc) · 947 Bytes
/
Copy pathMerge_Intervals.cpp
File metadata and controls
38 lines (36 loc) · 947 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
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool mycmp(Interval a, Interval b)
{
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
sort(intervals.begin(), intervals.end(), mycmp);
vector<Interval> result;
int i = 0;
while (i < intervals.size()) {
Interval c = intervals[i];
int next = i + 1;
while (next < intervals.size()) {
if (intervals[next].start <= c.end) { //overlap
c.end = max(c.end, intervals[next].end);
next++;
} else {
break;
}
}
result.push_back(c);
i = next;
}
return result;
}
};