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

Merge Intervals

时间:2015-08-21 15:09:25      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

Description:

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

Code:

   int partition(vector<Interval>& intervals, int low, int high)
    {
        Interval key(intervals[low].start, intervals[low].end);
        while (low<high){
            while (low < high && intervals[high].start>=key.start)--high;
            intervals[low].start = intervals[high].start;
            intervals[low].end = intervals[high].end;
            
            while (low < high && intervals[low].start<=key.start)++low;
            intervals[high].start = intervals[low].start;
            intervals[high].end = intervals[low].end;
        }
            intervals[low].start = key.start;
            intervals[low].end = key.end;
            return low;
    }
    void quickSort(vector<Interval>& intervals, int low, int high)
    {
        if (low < high)
        {
            int pos = partition(intervals,low,high);
            quickSort(intervals, low, pos);
            quickSort(intervals, pos+1,high);
        }
    }
    void quickSort(vector<Interval>& intervals){
        quickSort(intervals,0,intervals.size()-1);
    }
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval>result;
        quickSort(intervals);
        unsigned int n = intervals.size();
        if (n==0)
            return result;
        result.push_back(intervals[0]);
        for (int i = 1; i < n; ++i)
        {
            int temp = result.size();
            if (intervals[i].start <= result[temp-1].end)
                result[temp-1].end = max(intervals[i].end,result[temp-1].end);
            else
                result.push_back(intervals[i]);
        }
        return result;
    }

技术分享

Merge Intervals

标签:

原文地址:http://www.cnblogs.com/happygirl-zjj/p/4747671.html

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