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

/**
 * 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:
    static int cmp(const Interval a, const Interval b)
    {
        if (a.start < b.start) return true;
        return false;
    }
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> ret;
        if (intervals.empty()) return ret;
        sort(intervals.begin(), intervals.end(),cmp);
        for (auto ite: intervals)
        {
            if (ret.empty() || ret.back().end < ite.start) ret.push_back(ite);
            else ret.back().end = max(ite.end, ret.back().end);
        }
        return ret;
    }
};
点赞