-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeInterval.cpp
More file actions
37 lines (30 loc) · 954 Bytes
/
Copy pathMergeInterval.cpp
File metadata and controls
37 lines (30 loc) · 954 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
/**
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].
*/
class Solution {
public:
struct sorter {
bool operator() (const Interval& lhs, const Interval& rhs) {
return lhs.start < rhs.start;
}
};
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> ret;
if (intervals.empty()) return ret;
std::sort(intervals.begin(), intervals.end(), sorter());
ret.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); ++i) {
Interval currInterval = ret.back();
if (intervals[i].start > currInterval.end) {
ret.push_back(intervals[i]);
}
else {
ret.back().end = std::max(currInterval.end, intervals[i].end);
}
}
return ret;
}
};