Leetcode 56. Merge Intervals (Hard) (cpp)
Tag: Array, Sort
Difficulty: Hard
/*
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].
*/
/**
* 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) {
if (intervals.empty()) {
return {};
}
sort(intervals.begin(), intervals.end(), [] (Interval a, Interval b) {return a.start < b.start;});
vector<Interval> res;
res.push_back(intervals[0]);
int i = 0, j = 1;
while (j < intervals.size()) {
if (res[i].end >= intervals[j].start) {
res[i].start = min(res[i].start, intervals[j].start);
res[i].end = max(res[i].end, intervals[j].end);
j++;
} else {
res.push_back(intervals[j++]);
i++;
}
}
return res;
}
};