A very simple accepted C++ readable solution O(nlogn)


  • 0
    R
    bool comp(Interval a, Interval b) {
        return a.start < b.start;
    }
    
    class Solution {
    public:
        vector<Interval> merge(vector<Interval>& intervals) {
            vector<Interval> res;
            if(intervals.size() == 0)
                return res;
            sort(intervals.begin(), intervals.end(), comp);
            Interval prev = intervals[0];
            for(int i = 1 ; i < intervals.size() ; ++i) {
                if(intervals[i].start > prev.end) {
                    res.push_back(prev);
                    prev = intervals[i];
                }
                else
                    if(intervals[i].end > prev.end)
                        prev.end = intervals[i].end;
            }
            res.push_back(prev);
            return res;
        }
    };

Log in to reply
 

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