idea: sort by the first dimension and then do it in a natural way.
bool operator<(const Interval &v1, const Interval &v2) { return v1.start < v2.start; }
class Solution {
public:
vector<Interval> merge(vector<Interval> &intervals) {
vector<Interval> cc;
sort(intervals.begin(), intervals.end());
int n = intervals.size();
int i = 0;
while(i < n) {
cc.push_back(intervals[i++]);
while(i < n && intervals[i].start <= cc.back().end)
cc.back().end = max(cc.back().end, intervals[i++].end);
}
return cc;
}
No comments:
Post a Comment