leetcode[56]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 comp(const Interval &a, const Interval &b)

{

    if(a.start==b.start)return a.end<b.end;

    return a.start<b.start;

}

class Solution {

public:

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

{    

    vector<Interval> res;

    if(intervals.empty())return res;    

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

    Interval temp(intervals[0].start, intervals[0].end);

    for (int i=1;i<intervals.size();i++)

    {

        if (intervals[i].start<=temp.end)

        {

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

        } 

        else

        {

            res.push_back(temp);

            temp.start=intervals[i].start;

            temp.end=intervals[i].end;

        }

    }

    res.push_back(temp);

    return res;

}

};

 

你可能感兴趣的:(LeetCode)