56. Merge Intervals (Hard)
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]
.
Solution 1: Array, Sort 9ms
这道和之前那道 Insert Interval 插入区间 很类似,这次题目要求我们合并区间,之前那题明确了输入区间集是有序的,而这题没有,所有我们首先要做的就是给区间集排序,由于我们要排序的是个结构体,所以我们要定义自己的comparator,才能用sort来排序,我们以start的值从小到大来排序,排完序我们就可以开始合并了,首先把第一个区间存入结果中,然后从第二个开始遍历区间集,如果结果中最后一个区间和遍历的当前区间无重叠,直接将当前区间存入结果中,如果有重叠,将结果中最后一个区间的end值更新为结果中最后一个区间的end和当前end值之中的较大值,然后继续遍历区间集,以此类推可以得到最终结果,代码如下:
/**
* 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 {
struct Compare {
bool operator() (const Interval &a, const Interval &b) {
// get the field to sort by and make the comparison
return (a.start < b.start);
}
};
static bool comp(const Interval &a, const Interval &b) {
return (a.start < b.start);
}
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
if (intervals.empty()) return res;
sort(intervals.begin(), intervals.end(), comp); // Compare()
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;
}
};
version 2:
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
if (intervals.empty()) return {};
sort(intervals.begin(), intervals.end(), [](Interval&a, Interval&b){return a.start < b.start;});
vector<Interval> res = {intervals[0]};
for (int i = 1; i < intervals.size(); ++i) {
if (res.back().end < intervals[i].start) res.push_back(intervals[i]);
else {
res.back().end = max(intervals[i].end, res.back().end);
}
}
return res;
}
};
Solution 2:
这道题还有另一种解法,这个解法直接调用了之前那道题 Insert Interval 插入区间 的函数,由于插入的过程中也有合并的操作,所以我们可以建立一个空的集合,然后把区间集的每一个区间当做一个新的区间插入结果中,也可以得到合并后的结果,代码如下:
/**
* 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 {
vector<Interval> insert(vector<Interval>& intervals, Interval newInterval) {
vector<Interval> res = intervals;
auto it = res.begin();
int overlap = 0;
while (it != res.end()) {
// new interval shouble be placed before current iterator
if (newInterval.end < it->start) break;
// new interval shouble be placed after current iterator
if (newInterval.start > it->end) {
++it;
continue;
}
// has overlapping
newInterval.start = min(newInterval.start, it->start);
newInterval.end = max(newInterval.end, it->end);
++overlap;
++it;
}
if (overlap) it = res.erase(it-overlap, it);
res.insert(it, newInterval);
return res;
}
public:
vector<Interval> merge(vector<Interval>& intervals) {
vector<Interval> res;
for (int i = 0; i < intervals.size(); ++i) {
res = insert(res, intervals[i]);
}
return res;
}
};