Leetcode 56. 合并区间

对所有区间按起点位置进行排序
遍历到k点后的[l,r]:已知的包含k点的最大区间
遍历到k+1点,若该起点属于[l,r]那么可能扩展这个区间的终点,r=max(r,k+1点的end)

/**
* 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 merge(vector& intervals) {
        vector ans;
        sort(intervals.begin(), intervals.end(),
            [](const Interval a, const Interval b) {return a.start < b.start; });
        if (intervals.empty()) return ans;
        int l = intervals[0].start, r = intervals[0].end;
        for (auto &x : intervals)
            if (x.start >= l && x.start <= r) r = max(x.end, r);
            else ans.push_back(Interval(l, r)), l = x.start, r = x.end;
            ans.push_back(Interval(l, r));
            return ans;
    }

};

你可能感兴趣的:(Leetcode 56. 合并区间)