码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Intervals

时间:2014-06-04 20:45:31      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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].

bubuko.com,布布扣
/**
 * 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 {
private:
    void quicksort(vector<Interval> & datas,int left,int right)
    {
        if(left>=right) 
            return;
        int l=left;
        int r=right;
        int m=datas[(l+r)/2].start;
        while(l<=r)
        {
            while(datas[l].start<m) l++;
            while(datas[r].start>m) r--;
            if(l>right || r<left || l>=r)
                break;
            
            Interval tmp=datas[l];
            datas[l]=datas[r];
            datas[r]=tmp;
            l++;r--;
        }
        
        quicksort(datas,left,l-1);
        quicksort(datas,r+1,right);
    }
    inline bool checkoverlap(const Interval& interval1,const Interval& interval2)
    {
        if(interval1.start<=interval2.start && interval1.end>=interval2.end) return true;
        if(interval1.start<=interval2.start && interval1.end>=interval2.start) return true;
        if(interval1.start<=interval2.end && interval1.end>=interval2.end) return true;
        return false;
    }
    inline void mergeinterval(Interval& interval1,const Interval& interval2)
    {
        if(interval1.start>interval2.start) interval1.start=interval2.start;
        if(interval1.end<interval2.end) interval1.end=interval2.end;
    }
public:
    vector<Interval> merge(vector<Interval> &intervals) 
    {
        vector<Interval> v;
        if(intervals.size()==0return v;
        
        //sort by start
        quicksort(intervals,0,intervals.size()-1);
        //merge
        
        int index=0;
        v.push_back(intervals[0]);
        
        for(int i=1;i<intervals.size();i++)
        {
            if(checkoverlap(v[index],intervals[i]))
            {
                mergeinterval(v[index],intervals[i]);
            }
            else
            {
                v.push_back(intervals[i]);
                index++;
            }
        }
        
        return v;
    }
}; 
bubuko.com,布布扣

Merge Intervals,布布扣,bubuko.com

Merge Intervals

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/erictanghu/p/3759406.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!