LeetCode 56. Merge Intervals

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].

The basic idea is to sort the intervals increasingly based on the .start value. Then, merge them one by one until merge fails.


static bool sorter(Interval start, Interval end) {
    return start.start < end.start;
}

static bool merge(Interval& v1, Interval& v2, Interval& res) {
    if(v1.end < v2.start) return false;
    res.start = v1.start;
    res.end = max(v1.end, v2.end);
    return true;
}

vector<Interval> merge(vector<Interval>& intervals) {
    if(intervals.size() == 0) return {};
    sort(intervals.begin(), intervals.end(), sorter);
    vector<Interval> res;
    res.push_back(intervals[0]);
    Interval tmp;
    for(int i = 1; i < intervals.size(); ++i) {
        if(merge(res.back(), intervals[i], tmp)) {
            res.back() = tmp;
        } else {
            res.push_back(intervals[i]);
        }
    }
    return res;
}


你可能感兴趣的:(LeetCode 56. Merge Intervals)