forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervals.cpp
More file actions
35 lines (33 loc) · 1.02 KB
/
MergeIntervals.cpp
File metadata and controls
35 lines (33 loc) · 1.02 KB
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
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool myfunction (Interval i,Interval j) { return (i.start<j.start); }
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> mergedIntervals;
if(intervals.size()==0) {
return mergedIntervals;
}
sort(intervals.begin(), intervals.end(), myfunction);
int start = intervals[0].start;
int end = intervals[0].end;
for(int i=1;i<intervals.size(); ++i) {
if(intervals[i].start <= end) {
end = max(end, intervals[i].end);
} else {
mergedIntervals.push_back(Interval(start, end));
start = intervals[i].start;
end = intervals[i].end;
}
}
mergedIntervals.push_back(Interval(start,end));
return mergedIntervals;
}
};