原题
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].
思路
先排序后merge
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:
static bool cmp(const Interval& a, const Interval& b) {
/// here use '<' operator instead of '<=' operator
/// othwise, 'time limit exceeded' or 'runtime error' occurs!
/// i don't know why
return a.start < b.start;
}
vector<Interval> merge(vector<Interval>& intervals) {
int len = intervals.size();
if(len <= 1) return intervals;
/// sort -- use static member funtion
std::sort(intervals.begin(), intervals.end(), Solution::cmp);
/// init
vector<Interval> res;
/// method1
Interval tmp = intervals[0];
for(int i = 1; i < len; i++) {
if(tmp.end >= intervals[i].start) {
tmp.end = max(tmp.end, intervals[i].end);
} else {
res.push_back(tmp);
tmp.start = intervals[i].start;
tmp.end = intervals[i].end;
}
}
res.push_back(tmp);
/// method 2
// res.push_back(intervals[0]);
// for (int i = 1; i < intervals.size(); i++){
// if (res.back().end >= intervals[i].start){
// res.back().end = max(res.back().end, intervals[i].end);
// }else{
// res.push_back(intervals[i]);
// }
// }
return res;
}
};