题目:
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 considered overlapping.
NOTE: input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
描述:
给出若干表示区间的数对,要求将可以合并的区间合并后返回
分析:
nlogn 的解法:
先将区间按照起始的位置升序排列,再按照贪心的思想,
如果当前的区间能够和最近的区间合并,则进行合并,详情见代码
提交了之后,只超越了不到一半的提交者,难道这道题还有线性解法??
然后搜了题解,发现貌似只有这一种解法,暂时不清楚哪里影响到了运行速度...
代码:(时间复杂度 O(n * log n))
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
if (intervals.size() < 2) {
return intervals;
}
sort(intervals.begin(), intervals.end(), cmp);
vector<vector<int>> result;
result.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); ++ i) {
int last_index = result.size() - 1;
if (result[last_index][1] >= intervals[i][0]) {
result[last_index][1] = max(result[last_index][1], intervals[i][1]);
} else {
result.push_back(intervals[i]);
}
}
return result;
}
static bool cmp(const vector<int> &a, const vector<int> &b) {
return a[0] < b[0];
}
};