C++_Sort_Accepted_19ms_38.65%


  • 0

    It is very easy if you can rewrite the sort() function in STL.

    class Solution {
    public:
    vector<Interval> merge(vector<Interval>& intervals) {
        if(intervals.empty() || intervals.size() == 1) return intervals;
        sort(intervals.begin(), intervals.end(),[](Interval a, Interval b){
          return a.start < b.start || (a.start ==  b.start && a.end <  b.end);
        });
        vector<Interval> res;
        int n = intervals.size();
        for(int i = 1; i < n; i++){
            if(intervals[i-1].end < intervals[i].start){res.push_back(intervals[i-1]);}
            else if(intervals[i-1].end >= intervals[i].start){
                intervals[i].start = intervals[i-1].start;
                intervals[i].end = max(intervals[i-1].end,intervals[i].end);
            }
            if(i + 1 == n){res.push_back(intervals[i]);}
        }
        return res;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.