Tag:leetcode fb
Category:Leetcode
Article From:https://www.cnblogs.com/JTechRoad/p/9060127.html

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;
    }
};

 

Link of this Article: 56. Merge Intervals

Leave a Reply

Your email address will not be published. Required fields are marked *