C++ clean code to insert the interval


  • 0
    J
    /**
     * 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) {
            sort(intervals.begin(),intervals.end(),[](Interval &a,Interval &b){return a.start<b.start;});
            vector<Interval> result;
            int n = intervals.size();
            if(n==0) return result;
            Interval pre = intervals[0];
            for(int i = 1;i<intervals.size();i++)
            {
                if(intervals[i].start>pre.end)
                {
                    result.push_back(pre);
                    pre = intervals[i];
                }
                else
                {
                    pre.end = max(intervals[i].end,pre.end);
                }
            }
            result.push_back(pre);
            return result;
        }
    };
    

Log in to reply
 

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