LeetCode_Merge Intervals

Given a collection of intervals, merge all overlapping intervals.



For example,

Given [1,3],[2,6],[8,10],[15,18],

return [1,6],[8,10],[15,18].

  

/**

 * Definition for an interval.

 * struct Interval {

 *     int start;

 *     int end;

 *     Interval() : start(0), end(0) {}

 *     Interval(int s, int e) : start(s), end(e) {}

 * };

 */

 

    bool sortM(const  Interval &a1, const  Interval &a2)

    {

      return a1.start < a2.start ;

    }

class Solution {

public:

   

    vector<Interval> merge(vector<Interval> &intervals) {

       

        int n = intervals.size();

        if(intervals.size() <2) return intervals;

        sort(intervals.begin(),intervals.end(),sortM);

        

        int i,max;

        Interval next,val = intervals[0]; 

        vector<Interval> result;

        

        for(i = 1; i< n; i++)

        {

            if(intervals[i].start > val.end){                 

                 result.push_back(val);

                 val = intervals[i] ;

            }else{

               val.end = val.end >intervals[i].end ? val.end : intervals[i].end;

            }

        } //end of for i

        result.push_back(val) ; 

        return result ;

      

    }

};

 

你可能感兴趣的:(LeetCode)