【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)
Merge Intervals
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 considerred overlapping.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
//问题:区间合并
/*
方法:将各区间按照第一个元素排序,如果没有重叠,逐个将区间push到结果容器中,
如果有重叠,进行区间合并,修改前一个区间第二个元素即可
*/
class Solution
{
public:
//自定义函数对象排序(或声明为static类型的函数也可以)
struct
{
bool operator()(Interval& a, Interval& b)//这里用Interval&引用变量比较好,节省时间
{
return a.start<b.start;
}
} customLess;
vector<Interval> merge(vector<Interval>& ins)
{
vector<Interval> res;
if(ins.empty()) return res;
sort(ins.begin(), ins.end(),customLess);//按第一个变量排序
res.push_back(ins[0]);
for(int i=1; i<ins.size(); i++)
{
if(ins[i].start > res.back().end) res.push_back(ins[i]); //如果没有重叠时
else res.back().end = max(res.back().end, ins[i].end); //如果有重叠时,end选较大的那个
}
return res;
}
};