-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergeIntervals.cpp
66 lines (60 loc) · 1.79 KB
/
mergeIntervals.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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/*
* mergeIntervals.cpp
*
* Created on: Jun 26, 2016
* Author: gokul
*/
#include <vector>
using namespace std;
/**
* 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:
// b is contained in a
bool containedIn(Interval* a, Interval* b) {
return (a->start <= b->start && a->end >= b->end);
}
vector<Interval> merge(vector<Interval>& intervals) {
if (intervals.empty() || intervals.begin() == intervals.end()) {
return intervals;
}
std::sort(intervals.begin(), intervals.end(), [](Interval a, Interval b) { return a.end == b.end ? a.start < b.start : a.end < b.end; });
vector<Interval> res;
res.push_back(intervals[0]);
for (auto it = intervals.begin() + 1; it != intervals.end(); ++it) {
auto last = &res.back();
if (it->start > last->end) {
res.push_back(*it);
continue;
}
if (it->start <= last->end) {
last->end = it->end;
}
if (it->start < last->start) {
last->start = it->start;
}
}
std::sort(res.begin(), res.end(), [](Interval a, Interval b) { return a.start < b.start; });
vector<Interval> final;
final.push_back(res[0]);
for (auto it = res.begin() + 1; it != res.end(); ++it) {
auto last = &final.back();
if (containedIn(last, &(*it))) {
continue;
}
if (it->start <= last->end) {
last->end = it->end;
continue;
}
final.push_back(*it);
}
return final;
}
};