题目:
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
思路:
首先对区间进行排序,然后线性扫描:如果当前区间和上一个区间有重合,则和上一个区间合并,否则就新添加一个区间。时间复杂度为O(nlogn)(注意总体时间复杂度是排序的复杂度,而对排好序的区间进行合并的复杂度为O(n))。空间复杂度为O(1)。
代码:
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> result;
if(intervals.empty())
return result;
sort(intervals.begin(), intervals.end(), comp);
result.push_back(intervals[0]);
for(int i = 1; i < intervals.size();++i)
{
if(intervals[i].start <= result.back().end)
result.back().end = max(result.back().end, intervals[i].end);
else
result.push_back(intervals[i]);
}
return result;
}
private:
static bool comp(const Interval& a, const Interval& b)
{
if(a.start < b.start)
return true;
else if(a.start > b.start)
return false;
else
return a.end < b.end;
}
};