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

LeetCode: Merge Intervals [055]

时间:2014-05-24 14:18:27      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:leetcode   算法   面试   

【题目】


Given an array of non-negative integers, you are initially positioned at the first index of the array.

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 compare(const Interval&o1, const Interval&o2){
     if(o1.start<o2.start)return true;
     else if(o1.start==o2.start){
         return o1.end<o2.end;
     }
     return false;
 }
 
class Solution {
public:
    vector<Interval> merge(vector<Interval> &intervals) {
        vector<Interval> result;
        int size=intervals.size();
        if(size==0)return result;
        //排序
        sort(intervals.begin(), intervals.end(),compare);
        //合并
        Interval curInterval(intervals[0].start, intervals[0].end);
        for(int i=1; i<size; i++){
            if(curInterval.end<intervals[i].start){
                result.push_back(curInterval);
                curInterval=Interval(intervals[i].start, intervals[i].end);
            }
            else{
                if(intervals[i].end>curInterval.end)curInterval.end=intervals[i].end;
            }
        }
        //别忘了最后一个区间
        result.push_back(curInterval);
        return result;
    }
};


LeetCode: Merge Intervals [055],布布扣,bubuko.com

LeetCode: Merge Intervals [055]

标签:leetcode   算法   面试   

原文地址:http://blog.csdn.net/harryhuang1990/article/details/26744153

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