Leetcode -- Merge Intervals
来源:互联网 发布:js 将图片转为base64 编辑:程序博客网 时间:2024/05/21 14:51
https://oj.leetcode.com/problems/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]
.
public List<Interval> merge(List<Interval> intervals)
分析:这一题要分两步。第一步是排序,根据interval的左值排序。
第二步才是合并。首先我们需要维护一个用来判断是否合并或者直接插入的变量interval X,合并的步骤分两种情况讨论,第一种情况是合并,其实就是X的右值大于等于当前遍历到的interval的左值,这个时候更新X的右值如果当前遍历到的interval的右值大于X的右值。第二种情况则是插入,也就是X的右值小于当前遍历到的interval,这个时候就是不存在overlap了,那么就将X插入新的结果数组,然后当前的Interval就成为新的X进行之后的操作。给出代码如下:
public List<Interval> merge(List<Interval> intervals) { Collections.sort(intervals, new IntervalComparator()); List<Interval> res = new LinkedList<Interval>(); if(intervals.size() == 0) return res; int curstart = intervals.get(0).start; int curend = intervals.get(0).end; for(int i = 1; i < intervals.size(); i++){ Interval tmp = intervals.get(i); if(tmp.start > curend){ res.add(new Interval(curstart, curend)); curstart = tmp.start; curend = tmp.end; }else{ curend = Math.max(tmp.end, curend); } } res.add(new Interval(curstart, curend)); return res; } public class IntervalComparator implements Comparator<Interval>{ @Override public int compare(Interval a, Interval b){ return (new Integer(a.start)).compareTo(new Integer(b.start)); } }
0 0
- LeetCode: Merge Intervals
- LeetCode Merge Intervals
- LeetCode: Merge Intervals
- [Leetcode] Merge Intervals
- leetcode 28: Merge Intervals
- Leetcode: Merge Intervals
- [LeetCode] Merge Intervals
- [LeetCode]Merge Intervals
- leetcode merge intervals
- [leetcode]Merge Intervals
- LeetCode-Merge Intervals
- [leetcode] Merge Intervals
- LeetCode - Merge Intervals
- 【leetcode】Merge Intervals
- leetcode Merge Intervals
- LeetCode Merge Intervals
- [LeetCode] Merge Intervals
- LeetCode | Merge Intervals
- Spring基于annotation的AOP(AspectJ)
- Oracle ERP系統借贷关系表
- 自定义协议消息推送开源项目-CIM
- 一个高端.net技术人才的2014年度总结
- Hive基础概念
- Leetcode -- Merge Intervals
- 串口理解
- hdu 3496 Watch The Movie 二维费用背包
- 西门子PLC学习笔记二十一-(中断处理一)
- mysql命令
- 机器学习-协同过滤
- checkbox
- Xcode6为什么干掉pch&&如何添加pch文件
- UIImageView 圆角