【leetcode】56. Merge Intervals

原创 2015年07月10日 11:13:53
@requires_authorization 
@create_time 2015.7.10 11:07
@author johnsondu
@url https://leetcode.com/problems/merge-intervals/
/**
 *  进行数组排序,然后按照贪心策略进行合并,具体是考察
 *  下一个元素的start是否是介于当前的start和end之间,
 *  如果是,则根据需要更新当前end。
 *  时间复杂度(O(nlogn))-->排序, 结果获取O(n)
 *  空间复杂度(O(n))
 */

/**
 * 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 {
public:
    static bool cmp(const Interval &a, const Interval &b){
        if(a.start == b.start) return a.end < b.end;
        return a.start < b.start;
    }

    vector<Interval> merge(vector<Interval>& intervals) {
        int len = intervals.size();
        sort(intervals.begin(), intervals.end(), cmp);

        vector<Interval> ans;
        for(int i = 0; i < len; i ++){
            int st = intervals[i].start;
            int ed = intervals[i].end;
            int idx = i + 1;
            while(idx < len){
                if(intervals[idx].start >= st && intervals[idx].start <= ed){
                    if(intervals[idx].end > ed) ed = intervals[idx].end;
                    idx ++;
                }
                else break;
            }
            Interval tmp(st, ed);
            ans.push_back(tmp);
            i = idx - 1;
        }

        return ans;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

LeetCode 56:Merge Intervals

Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8...

LeetCode --- 56. Merge Intervals

题目链接:Merge Intervals Given a collection of intervals, merge all overlapping intervals. For example...

LeetCode_56---Merge Intervals

Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[...

Leetcode #56. Merge Intervals 间隔合并 解题报告

1 解题思想这道题虽然标记的是Hard,但是我觉得至多Middle的难度吧,题目是给了很多区间,中间可能有重叠,现在就让你将他进行合并。首先对于这个问题,我们肯定要排序!按照什么排序么?,注意到我们是...

leetcode题解-55. Jump Game && 56. Merge Intervals

55, 题目:Given an array of non-negative integers, you are initially positioned at the first index of t...

[LeetCode]56.Merge Intervals

【题目】 Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[...

LeetCode 56. Merge Intervals

LeetCode 56. Merge Intervals

[leetcode]56. Merge Intervals(Java)

https://leetcode.com/problems/merge-intervals/#/description Given a collection of interva...

leetCode 56.Merge Intervals (合并区间) 解题思路和方法

Merge Intervals  Given a collection of intervals, merge all overlapping intervals. For example...

leetcode || 56、 Merge Intervals

problem: Given a collection of intervals, merge all overlapping intervals. For example...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)