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

Merge Intervals

时间:2015-11-30 00:33:52      阅读:185      评论:0      收藏:0      [点我收藏+]

标签:

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

主要是考虑几种情况:

1.起点重复的区间

2.某区间包含另一个区间

/**
 * 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 compInterval(const Interval& lhs,const Interval& rhs){
     if(lhs.start == rhs.start){
         return lhs.end < rhs.end;
     }
     return lhs.start < rhs.start;
 }
class Solution {
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> res;
        int intervalsSize = intervals.size();
        if(intervalsSize ==0){
            return res;
        }
        sort(intervals.begin(),intervals.end(),compInterval);
        int i=0,j=1;
        while(i<intervalsSize){
            int k = j;
            while((k < intervalsSize) && (intervals[k].start == intervals[k-1].start)){//处理相同起点的区间
                k++;
            }
            i = k-1;
         
            int start = intervals[i].start;
            int end = intervals[i].end;
            while((k < intervalsSize) && (intervals[k].start > start && intervals[k].start <= end)){
                end = max(end,intervals[k].end);
                k++;
            }
            if(k==j){
                j = i;
            }else{
                j = k-1;
            }
            res.push_back(Interval(intervals[i].start,end));
            i = j+1;
            j = i+1;
        }
        return res;
    }
};

 

Merge Intervals

标签:

原文地址:http://www.cnblogs.com/zengzy/p/5005848.html

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