描述
把有重合的区间合并在一起
解决
先排序,然后贪心遍历
/**
* 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) {
int length = intervals.size();
if (length <= 1)
return intervals;
sort(intervals.begin(), intervals.end(), comp);
vector<Interval> res;
for (int i = 0; i < length; ++i)
{
int st = i, end = intervals[i].end;
while (i < length - 1 && end >= intervals[i + 1].start)
{
if (end < intervals[i + 1].end)
end = intervals[i + 1].end;
++i;
//cout << i << endl;
}
// cout << i;
res.push_back(Interval(intervals[st].start, end));
}
return res;
}
static bool comp(Interval a, Interval b)
{
return a.start == b.start ? a.end < b.end : a.start < b.start;
}
};