题目:
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]
.
Subscribe to see which companies asked this question.
解题思路:
使用sort对vector<Interval>首元素进行升序排序。这里需要匿名函数的相关知识(http://www.cnblogs.com/pzhfei/archive/2013/01/14/lambda_expression.html)。
Code:
/**
* 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> v;
if(intervals.empty()) return v;
sort(intervals.begin(),intervals.end(),[](Interval a, Interval b){return a.start< b.start;}); //这个地方"[]"为匿名函数。按照每个数组的首元素升序排列。
v.push_back(intervals[0]);
for(int i = 1; i< intervals.size();i++)
{
if(v.back().end >= intervals[i].start) //这里的等号必不可少。如[1,4],[4,5]的情况
{
v.back().end = max(v.back().end, intervals[i].end);
}
else
{
v.push_back(intervals[i]);
}
}
return v;
}
};