-
Notifications
You must be signed in to change notification settings - Fork 2
/
merge_intervals.cc
57 lines (51 loc) · 1.45 KB
/
merge_intervals.cc
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 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].
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
/**
* I will add some comments later.
*/
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
sort(intervals.begin(), intervals.end(), &myfunction);
deque<Interval> dq;
vector<Interval> result;
if (intervals.size() == 0) {
return result;
}
// add a pivot
dq.push_back(Interval(INT_MIN, INT_MIN + 1));
for(int i = 0; i < intervals.size();) {
if (intervals[i].start > dq.back().end) {
dq.push_back(intervals[i]);
i++;
}
else if (intervals[i].start <= dq.back().end && intervals[i].start >= dq.back().start) {
dq.back().end = intervals[i].end;
i++;
}
else {
dq.pop_back();
}
}
// remove the pivot
dq.pop_front();
while (!dq.empty()) {
result.push_back(dq.front());
dq.pop_front();
}
return result;
}
bool static myfunction(Interval i, Interval j) { return (i.end < j.end); }
};