Given a collection of intervals, merge all overlapping intervals.
Example
Given intervals => merged intervals:
[ [
[1, 3], [1, 6],
[2, 6], => [8, 10],
[8, 10], [15, 18]
[15, 18] ]
]
Challenge
思路是先对start 进行排序, 然后一个个合并;
O(n log n) time and O(1) extra space.
注意比较函数的写法,一定要写在类外, 变成全局函数!!
/**
* Definition of Interval:
* classs Interval {
* int start, end;
* Interval(int start, int end) {
* this->start = start;
* this->end = end;
* }
*/
bool myfunction (Interval i, Interval j) { return (i.start < j.start); }
class Solution {
public:
/**
* @param intervals: interval list.
* @return: A new interval list.
*/
vector<Interval> merge(vector<Interval> &intervals) {
// write your code here
vector<Interval> res;
if (intervals.empty()) {
return res;
}
sort(intervals.begin(), intervals.end(), myfunction);
res.push_back(intervals[0]);
for (int i = 1; i < intervals.size(); i++) {
if (intervals[i].start <= res.back().end) {
res.back().end = max(res.back().end, intervals[i].end);
} else {
res.push_back(intervals[i]);
}
}
return res;
}
};