56. Merge Intervals

https://leetcode.com/problems/merge-intervals/description/

/**
 * 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) {
        auto comp = [](const Interval& i1, const Interval& i2) {
            return i1.start < i2.start || i1.start == i2.start && i1.end < i2.end;
        };
        sort(intervals.begin(), intervals.end(), comp);
        
        vector<Interval> res;
        if (intervals.empty())  return res;
        Interval cur = intervals[0];
        for (int i = 1; i < intervals.size(); i++) {
            if (intervals[i].start <= cur.end) {
                cur.end = max(cur.end, intervals[i].end);
            }
            else {
                res.push_back(cur);
                cur = intervals[i];
            }
        }
        res.push_back(cur);
        return res;
    }
};
原文地址:https://www.cnblogs.com/JTechRoad/p/9060127.html