Description
Given a collection of intervals, merge all overlapping intervals.
Example 1
Input: [[1,3],[2,6],[8,10],[15,18]]
Output: [[1,6],[8,10],[15,18]]
Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
Example 2
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [1,4] and [4,5] are considerred overlapping.
Solution 1(C++)
class Solution {
public:
vector<Interval> merge(vector<Interval>& ins) {
if (ins.empty()) return vector<Interval>{};
vector<Interval> res;
sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});
res.push_back(ins[0]);
for (int i = 1; i < ins.size(); i++) {
if (res.back().end < ins[i].start) res.push_back(ins[i]);
else
res.back().end = max(res.back().end, ins[i].end);
}
return res;
}
};
算法分析
我最开始打算两层遍历,但是很明显做复杂了,这样还不如先排序,然后就好做多了,关键就是如何排序。利用sort函数与Lambda表达式,可参考:
程序分析
Lambda表达式:
sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});