-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeIntervals.cpp
More file actions
executable file
·45 lines (40 loc) · 1.1 KB
/
MergeIntervals.cpp
File metadata and controls
executable file
·45 lines (40 loc) · 1.1 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
36
37
38
39
40
41
42
43
44
45
//
// MergeIntervals.cpp
// leetcode
//
// Created by witwolf on 5/11/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#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:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if(intervals.empty()){
return result;
}
sort(intervals.begin(), intervals.end(),[](const Interval& lhs,const Interval &rhs){
return (lhs.start < rhs.start || (lhs.start == rhs.start && lhs.end < rhs.end));
});
result.push_back(*intervals.begin());
for(auto &interval:intervals){
Interval &back = result.back();
if(back.end < interval.start){
result.push_back(interval);
}else if(back.end >= interval.start && back.end <= interval.end){
back.end = interval.end;
}
}
return result;
}
};