合并区间,先预处理排序。
然后每个区间枚举,看能不能合后面的合并即可。
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
|
int cmp(Interval a, Interval b) {
if(a.start == b.start)
return a.end < b.end;
return a.start < b.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
sort(intervals.begin(), intervals.end(), cmp);
vector<Interval> ans;
ans.clear();
if(intervals.size() <= 0) return ans;
Interval item = intervals[0];
for(int i = 1; i < intervals.size(); i++) {
if(item.end < intervals[i].start) {
ans.push_back(item);
item = intervals[i];
}
else {
if(item.end < intervals[i].end)
item.end = intervals[i].end;
}
}
ans.push_back(item);
return ans;
}
};
|