156.Merge Intervals-合并区间(容易题)
来源:互联网 发布:什么软件可以透视 编辑:程序博客网 时间:2024/06/05 14:20
合并区间
题目
给出若干闭合区间,合并所有重叠的部分。
样例
给出的区间列表 => 合并后的区间列表:
挑战
O(n log n) 的时间和 O(1) 的额外空间。
题解
先排序再合并。
/** * Definition of Interval: * public class Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } */class Solution { /** * @param intervals: Sorted interval list. * @return: A new sorted interval list. */ public class Solution { public ArrayList<Interval> merge(ArrayList<Interval> intervals) { if (intervals == null || intervals.size() <= 1) { return intervals; } Collections.sort(intervals, new IntervalComparator()); ArrayList<Interval> result = new ArrayList<Interval>(); Interval last = intervals.get(0); for (int i = 1; i < intervals.size(); i++) { Interval curt = intervals.get(i); if (curt.start <= last.end ) { last.end = Math.max(last.end, curt.end); } else { result.add(last); last = curt; } } result.add(last); return result; } private class IntervalComparator implements Comparator<Interval> { public int compare(Interval a, Interval b) { return a.start - b.start; } }}
Last Update 2016.9.7
0 0
- 156.Merge Intervals-合并区间(容易题)
- 【区间合并】Merge Intervals
- Merge Intervals 合并区间
- 合并区间 Merge Intervals
- LeetCode | Merge Intervals(合并区间间隔)
- LeetCode 56. Merge Intervals(合并区间)
- Leetcode 56 - Merge Intervals(区间合并)
- Merge Intervals 合并区间@LeetCode
- Merge Intervals 多区间合并
- LeetCode OJ 之 Merge Intervals(合并区间)
- LeetCode-56 Merge Intervals(合并区间)
- leetcode-56 Merge Intervals 合并区间
- 56. Merge Intervals 对区间进行合并
- Array----- 56. Merge Intervals(合并区间)
- LeetCode 56. Merge Intervals 合并区间
- leetcode 56. Merge Intervals 区间合并
- 【LeetCode-面试算法经典-Java实现】【056-Merge Intervals(区间合并)】
- leetCode 56.Merge Intervals (合并区间) 解题思路和方法
- java-jvm调优(二)
- Linux常用命令
- linux下python调试
- Android RecyclerView 使用完全解析 体验艺术般的控件
- JAVA第十一章复习
- 156.Merge Intervals-合并区间(容易题)
- 虚函数
- EditText输入限制
- 在Eclipse添加Android兼容包( v4、v7 appcompat )(转)
- RecyclerView的多布局
- Makefile学习笔记系列1:一个简单的Makefile
- 动态规划:单调减子序列
- FM学习笔记
- Eclipse+Maven创建webapp项目