56. Merge Intervals

题目

https://leetcode.com/problems/merge-intervals/description/

-w948

想法

先排序,按照第一个数升序
挨个看是否可以合并
这样真的可以嘛,感觉好简单的样子,与赞数不符啊

咦,还真这样AC了,这水题,为什么900+的赞,不懂不懂

答案

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) {}
* };
*/
static const auto ____ = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
if (intervals.empty())
return res;
sort(intervals.begin(), intervals.end(), [](Interval& a, Interval& b) {
return a.start < b.start;
});
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
Interval& last = res[res.size() - 1];
if (intervals[i].start <= last.end) {
last.end = max(last.end, intervals[i].end);
} else {
res.push_back(intervals[i]);
}
}
return res;
}
};