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 [,] and [,] overlaps, merge them into [,].
Example 2
Input: [[1,4],[4,5]]
Output: [[1,5]]
Explanation: Intervals [,] and [,] 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[]);
for (int i = ; 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表達式,可參考:
- C++—— Lambda表達式
程式分析
Lambda表達式:
sort(ins.begin(), ins.end(), [](Interval a, Interval b){return a.start < b.start;});