-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathMerge_Intervals.cpp
More file actions
26 lines (26 loc) · 850 Bytes
/
Merge_Intervals.cpp
File metadata and controls
26 lines (26 loc) · 850 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
/**
* 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:
static bool comparefunc (const Interval& a, const Interval& b) {
return a.start < b.start;
}
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> result;
if(intervals.empty()) return result;
sort (intervals.begin(), intervals.end(), comparefunc);
result.push_back(intervals[0]);
for(int i = 1; i < intervals.size(); ++i) {
if(intervals[i].start > result.back().end) result.push_back(intervals[i]);
else result.back().end = max(result.back().end, intervals[i].end);
}
return result;
}
};