Share my c++ code


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

Log in to reply
 

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