qingcheng奕  

https://oj.leetcode.com/problems/merge-intervals/

合并区间

//排序
sort(intervals.begin(),intervals.end(),CMPFUN);
bool CMPFUN(Interval a, Interval b)
{
    return a.start<b.start;
}
/**
 * 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 CMPFUN(Interval a, Interval b)
{
    return a.start<b.start;
}
    
class Solution {
public:    
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> ans;
        if(intervals.size() == 0)
            return ans;
            
        //排序
        sort(intervals.begin(),intervals.end(),CMPFUN);
        
        size_t index = 0;
        
        while(index < intervals.size())
        {
            int start = intervals[index].start;
            int end = intervals[index].end;
            while((index + 1< intervals.size()) && end >= intervals[index + 1].start)
            {
                if(end < intervals[index + 1].end)
                    end = intervals[index + 1].end;
                index++;
            }
            intervals[index].start = start;
            intervals[index].end = end;
            ans.push_back(intervals[index]);
            index++;
        }
        return ans;
    }
};

 

posted on 2014-07-27 16:23  qingcheng奕  阅读(118)  评论(0编辑  收藏  举报