-
Notifications
You must be signed in to change notification settings - Fork 10
/
merge-intervals.cpp
36 lines (32 loc) · 929 Bytes
/
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
35
36
// Time: O(nlogn)
// Space: O(1)
/**
* 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) {
if (intervals.empty()) {
return intervals;
}
sort(intervals.begin(), intervals.end(),
[](const Interval& a, const Interval& b) {
return a.start < b.start;
});
vector<Interval> result{intervals[0]};
for (int i = 1; i < intervals.size(); ++i) {
if (intervals[i].start <= result.back().end) {
result.back().end = max(result.back().end, intervals[i].end);
} else {
result.emplace_back(intervals[i]);
}
}
return result;
}
};