Merge Intervals

原创 2015年07月09日 07:55:11

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.
 * public class Interval {
 *     int start;
 *     int end;
 *     Interval() { start = 0; end = 0; }
 *     Interval(int s, int e) { start = s; end = e; }
 * }
 */
public class Solution {
    public List<Interval> merge(List<Interval> intervals) {
        
        ArrayList<Interval> result = new ArrayList<Interval>();
        if (intervals == null || intervals.size() <= 1)
            return intervals;
            
        Comparator<Interval> comp = new Comparator<Interval>() {
            public int compare(Interval i1, Interval i2) {
                return i1.start - i2.start;
            }
        };
        Collections.sort(intervals, comp);
        
        result.add(intervals.get(0));
        for (int i = 1; i < intervals.size(); i++) {
            if (result.get(result.size() - 1).end >= intervals.get(i).start) {
                result.get(result.size() - 1).end = Math.max(intervals.get(i).end, result.get(result.size() - 1).end);
            } else {
                result.add(intervals.get(i));
            }
        }
        
        
        return result;
    }
    
}


Merge Intervals And Insert Interval -- Leetcode

leetcode 中的两个集合操作题目: Merge Intervals , Insert Interval

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的难度吧,题目是给了很多区间,中间可能有重叠,现在就让你将他进行合并。首先对于这个问题,我们肯定要排序!按照什么排序么?,注意到我们是...
  • MebiuW
  • MebiuW
  • 2016年04月26日 23:54
  • 633

56. Merge Intervals\113. Path Sum II\211. Add and Search Word - Data structure design

Merge Intervals 题目描述 代码实现 Path Sum II 题目描述 代码实现56. Merge Intervals题目描述Given a collection of interval...

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】Merge Intervals

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

LeetCode Merge Intervals

这道题的要诀是:要会操作其end值。 1 需要排序 2 确定好开始值start,然后end值就可以跨过后面很多值了。 这些题的思路都不难,但是很烦,因为下标很不好处理。 精炼的程序是需要精炼的...

56. Merge Intervals 对区间进行合并

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

LeetCode—Merge Intervals

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

[LeetCode]56.Merge Intervals

【题目】 Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Merge Intervals
举报原因:
原因补充:

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