LeetCode 56. Merge Intervals(合并区间)
2016-05-21 07:14
537 查看
原题网址:https://leetcode.com/problems/merge-intervals/
Given a collection of intervals, merge all overlapping intervals.
For example,
Given
return
方法:按照开始点对区间进行排序,然后合并。
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) { Collections.sort(intervals, new Comparator<Interval>() { @Override public int compare(Interval i1, Interval i2) { return Integer.compare(i1.start, i2.start); } }); List<Interval> merged = new ArrayList<>(); for(int i=0; i<intervals.size(); i++) { if (i==0) { merged.add(intervals.get(i)); } else { Interval last = merged.get(merged.size()-1); if (last.start <= intervals.get(i).start && intervals.get(i).start <= last.end) { last.end = Math.max(last.end, intervals.get(i).end); } else { merged.add(intervals.get(i)); } } } return merged; } }
相关文章推荐
- 在线分享《如何针对业务做DB优化》(附PPT、录音、视频地址)
- linux下安装jdk
- centos x86_64--------------------------------系统调用
- Lambda表达式
- 留美CS学习的第一学期总结
- android Intent.ACTION_SEND
- 【bzoj4592】【SHOI2015】【脑洞治疗仪】【线段树】
- LeetCode 55. Jump Game(跳格子)
- 关于人事说话真假问题
- C++抽象类
- LeetCode 54. Spiral Matrix(螺旋矩阵)
- 英雄无敌3 Mac 百度云 下载
- 陶哲轩实分析-第6章-序列的极限
- MongoDB基本用法
- LeetCode 53. Maximum Subarray(最大子数组)
- Git 分支合并
- CentOS 7拨号上网(ADSL & PPPoE)
- C++代理
- 【华为OJ】【095-四则运算】
- java设计模式之模板方法模式