题目:
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]
.
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
bool cmp(Interval x, Interval y) {
return x.start < y.start;
}
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
if (intervals.size() == 0)
return intervals;
vector<Interval> ans;
sort(intervals.begin(), intervals.end(), cmp);
vector<Interval>::iterator it = intervals.begin();
vector<Interval>::iterator pre = it;
it++;
for (; it != intervals.end(); it++) {
if (pre->end < it->start) {
ans.push_back(*pre);
pre = it;
}
//相交
else
pre->end = max(pre->end, it->end);
}
ans.push_back(*pre);
return ans;
}
};