leetcode_c++:Merge_Intervals(056)

原创 2016年05月31日 22:44:28

题目

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


算法

复杂度:O(nm)


#include<iostream>
#include<vector>
#include <algorithm>

using namespace std;

const int N=0;


  struct Interval {
      int start;
      int end;
      Interval() : start(0), end(0) {}
      Interval(int s, int e) : start(s), end(e) {}
  };


bool isLess(const Interval &a, const Interval &b){
    return a.start<b.start;
}

class Solution{
    public:
    vector<Interval> merge(vector<Interval> &intervals){
        int nSize=intervals.size();
        vector<Interval>  result;
        if(nSize==0)
            return result;

        sort(intervals.begin(),intervals.end(),isLess);
        Interval val=intervals[0];
        Interval next;
        for(int i=1;i<nSize;++i){
            next=intervals[i];
            if(next.start>val.end){
                result.push_back(val);
                val=next;

            }else{
                val.end=val.end>next.end? val.end:next.end;
            }

        }

        result.push_back(val);
        return result;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

【LeetCode】Merge Intervals 解题报告

【题目】 Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[...
  • ljiabin
  • ljiabin
  • 2015年04月06日 20:32
  • 3988

LeetCode 56 Merge Intervals--In C++

思路: 主要想法是先从Intervals中取出所有的int值,封装到一个Node节点中,节点里保存了他是不是起点,与之匹配的值,和自己的值等3个信息。 然后对Node类型的数组workspace进...

LeetCode056 Merge Intervals

详细见:leetcode.com/problems/merge-intervals Java Solution: github package leetcode; import ja...
  • zxwtry
  • zxwtry
  • 2017年04月12日 18:49
  • 131

【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】

【056-Merge Intervals(区间合并)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a collection of intervals, me...

LeetCode 之 Merge Intervals — C++ 实现

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

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

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

[leetcode]Merge Intervals

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

leetcode || 56、 Merge Intervals

problem: Given a collection of intervals, merge all overlapping intervals. For example...

[Java]leetcode56 Merge Intervals

Given a collection of intervals, merge all overlapping intervals.For example, Given [1,3],[2,6],[8,...
  • fumier
  • fumier
  • 2015年08月18日 20:08
  • 651

【LeetCode】Merge Intervals 题解 利用Comparator进行排序

题目链接Merge Intervals /** * Definition for an interval. * public class Interval { * int sta...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode_c++:Merge_Intervals(056)
举报原因:
原因补充:

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