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].
思路:按照start排序,然后遍历全部元素,如果完全错开就放进去,如果没有完全错开就修改上一区间的end值。用vector.back()可以代替栈,更方便简洁。
/**
* 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:
static bool cmp(const Interval &a,const Interval &b) //必须要加 static,否则编译不给通过
{
return a.start<b.start;
}
vector<Interval> merge(vector<Interval>& v) {
int n = v.size();
stack<Interval> s;
vector<Interval> res;
if(n == 0)
return res;
sort(v.begin(),v.end(),cmp);
s.push(v[0]); //压入第一个区间
for(int i=1;i<n;i++)
{
Interval tmp = s.top();
if(v[i].start > tmp.end) //区间错开
s.push(v[i]);
else
{
if(v[i].end > tmp.end)
tmp.end = v[i].end;
s.pop();
s.push(tmp);
}
}
while(!s.empty())
{
Interval t = s.top();
s.pop();
res.push_back(t);
}
return res;
}
};