Insert Interval
来源:互联网 发布:长兴岛造船基地 知乎 编辑:程序博客网 时间:2024/06/09 21:47
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9]
, insert and merge[2,5]
in as[1,5],[6,9]
.
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16]
, insert and merge[4,9]
in as[1,2],[3,10],[12,16]
.
This is because the new interval [4,9]
overlaps with[3,5],[6,7],[8,10]
.
代码:
/** * 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; } * } */ class Interval implements Comparable<Interval>{int start;int end;Interval() { start = 0; end = 0; }Interval(int s, int e) { start = s; end = e; }public int compareTo(Interval o){return this.start - o.start;}}public class Solution { public List<Interval> insert(List<Interval> intervals, Interval newInterval){intervals.add(newInterval);Collections.sort(intervals);List<Interval> result = new ArrayList<Interval>(); int length = intervals.size(); if(length <= 1) return intervals; Interval first = intervals.get(0),second = new Interval(); for(int i = 1; i < length; i++) { second = intervals.get(i); if(second.start > first.end) { result.add(first); first = second; } else { first.end = Math.max(first.end, second.end);} } //最后一次合并 result.add(first); return result; }}
0 0
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- Insert Interval
- 最近比较闲,外加想敦促自己学习,所以来准备写博客了,请多指教
- VS2013 QT5.3.2中文显示乱码问题
- 向EditText或TextView中添加笑脸
- emmet下载安装
- 【iOS开发-10】UIProgressView进度条的几个属性介绍
- Insert Interval
- hdu1087——Super Jumping! Jumping! Jumping!
- collection与map详解
- POJ_2635_The Embarassed Cryptographer_同余定律
- 编辑距离算法
- 嵌入式学习笔记2—S3C2440的内存初始化
- 表达式求值思路
- 亚马逊云扩增磁盘 有图有真相
- Remove Duplicates from Sorted List