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

leetcode_56_Merge Intervals

时间:2015-02-11 18:42:12      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   array   sort   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


Merge Intervals

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


/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */

//方法:先sort,然后再考虑情况合并。复杂度:O(nlogn)
class Solution {
public:
    struct compare {
        bool operator()( const Interval& a , const Interval& b) const {
            if( a.start==b.start) 
                return a.end < b.end;
            else 
                return a.start < b.start;
        }
    };

	vector<Interval> merge(vector<Interval> &intervals) {
	    if(intervals.size()==0)
	        return vector<Interval>();
	    sort(intervals.begin() , intervals.end() , compare());
	    vector<Interval> ans;
	    Interval temp;
	    temp = intervals[0];
	    for(int i=1; i<intervals.size(); i++)
	    {
	        if(intervals[i].start <= temp.end )
	            temp.end = max(intervals[i].end , temp.end);
	        else
            {
                ans.push_back(temp);
                temp = intervals[i];
            }
	    }
	    ans.push_back(temp);
	    return ans;
	}
};


leetcode_56_Merge Intervals

标签:c++   leetcode   array   sort   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43735811

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