-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-intervals.cpp
More file actions
29 lines (29 loc) · 846 Bytes
/
merge-intervals.cpp
File metadata and controls
29 lines (29 loc) · 846 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
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> seg;
sort(intervals.begin(), intervals.end(),
[](Interval a, Interval b){return a.start < b.start;});
for (auto &pq : intervals) {
if (seg.empty()) {
seg.push_back(pq);
continue;
}
Interval &segTop = seg.back();
if (pq.start <= segTop.end) // merge or push_back
segTop.end = max(segTop.end, pq.end);
else
seg.push_back(pq);
}
return seg;
}
};