C++ solution with explanation clean code


  • 0
    H
    class Solution {
    public:
        vector<Interval> merge(vector<Interval>& intervals) {
            
            vector<Interval> result;
            if(intervals.empty())
                return result;
                
            //a lambda function introduced by C++11
            sort(intervals.begin(), intervals.end(), [](Interval &a, Interval &b){return a.start<b.start;});   
            int s = intervals[0].start;
            int e = intervals[0].end;
            for(int i=1; i<intervals.size(); i++)
            {
                //overlapping intervals
                if(intervals[i].start <= e)          
                {
                  e = max(intervals[i].end, e);       //update the max end
                }
                else
                {
                     // Disjoint intervals, add the previous one and reset bounds
                    result.push_back(Interval(s,e));
                    s = intervals[i].start;
                    e = intervals[i].end;
                }
            }
             // Add the last interval
            result.push_back(Interval(s,e));
            return result;
            
        }
    };
    

Log in to reply
 

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