题目要求
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].
下面是给定数对interval的结构体,需要将有重叠部分的数对合并起来,将合并后的数对数组输出
/*
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
解题思路
首先对给定的数对数组进行自定义排序,将start小的放在方面,自定义排序可以通过改造sort函数实现:
sort(vector.begin(),vector.end(),cmp);//cmp是函数名
static bool cmp(Interval &a, Interval &b);//cmp函数声明
注意:cmp比较函数必须写在类外部(全局区域)或声明为静态函数static。
将排好序的Interval数组逐个遍历,先把第一个数放进输出数组里,再依次访问后续数对,若数对的start<输出数组的最后一个元素的end,则更新最后一个元素的end;否则直接将该数对放入输出数组。是一个O(n)的算法复杂度。
C++代码
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
if (intervals.size()<2){
return intervals;
}
sort(intervals.begin(), intervals.end(), cmp);
vector<Interval> res;
res.push_back(intervals[0]);
for (int i = 1; i<intervals.size(); i++) {
if (res.back().end >= intervals[i].start) {
res.back().end = max(res.back().end, intervals[i].end);
}else{
res.push_back(intervals[i]);
}
}
return res;
}
static bool cmp(Interval &a, Interval &b) {
if (a.start < b.start) {
return true;
}
else {
return false;
}
}
};