Simple clean solution in C++, quite efficient 20ms


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

Log in to reply
 

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