对于给定的若干个区间,首先我们应该根据区间的左侧进行排序,然后遍历vector逐个比较或合并。
我们可以使用sort函数进行排序,但是由于vector中的数据类型是给定的Interval类型,所以我们需要重载操作符。按照Interval的start值进行从小到大排序。
然后首先将vector中的第一个元素push进res中,遍历给定的区间,每次都与res中最后一个元素进行比较,若是区间的左侧小于res中的右侧值,则说明有重叠区域(因为原给定的区间已经按照左侧值排序),此时应该将这个区间进行合并,更新res中的末尾元素;否则,说明没有重叠区域,直接将该区间添加至res中,直到遍历完毕。
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
struct Less{
bool operator()(const Interval& a, const Interval& b)
{
return a.start < b.start; //从小到大排序
}
};
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
int n=intervals.size();
vector<Interval>res;
if(n==0) return res;
sort(intervals.begin(),intervals.end(),Less());
res.push_back(intervals[0]);
for(int i=1;i<n;i++)
{
if(intervals[i].start<=res.back().end)
res.back().end=max(intervals[i].end,res.back().end);
else
res.push_back(intervals[i]);
}
return res;
}
};