Insert Interval
来源:互联网 发布:港口历年数据 编辑:程序博客网 时间:2024/06/06 06:59
题目:
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]
.
http://www.programcreek.com/2012/12/leetcode-insert-interval/
Thoughts of This Problem
Quickly summarize 3 cases. Whenever there is intersection, created a new interval.
赞!!!case 1 2,都是直接把new加入结果集中;
case3,是得到new和current的左端最小值,右端最大值,然后组合成一个interval加入结果集中
参考代码如下:
/** * 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 ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { ArrayList<Interval> result = new ArrayList<Interval>(); for(Interval interval: intervals){ if(interval.end < newInterval.start){ result.add(interval); }else if(interval.start > newInterval.end){ result.add(newInterval); newInterval = interval; }else if(interval.end >= newInterval.start || interval.start <= newInterval.end){ newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(newInterval.end, interval.end)); } } result.add(newInterval); return result; }}
- 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
- CF#321-D - Kefa and Dishes-状压DP+bitmasks
- Android开发之基础-------------Get请求和Post请求
- hdu 1241 Oil Deposits(dfs)
- 从酷狗的网络红歌说起
- Springmvc Hello World
- Insert Interval
- JAVA实现判断树的子结构及树的镜像问题(《剑指offer》)
- ListView与ViewPager组合(二)
- 条款25:全特化和偏特化
- Linux Shell学习笔记2:基本的bash shell命令
- mysql 安装
- C++中“浅拷贝”与“深拷贝”
- ZOJ-3892- Available Computation Sequence【区间dp】
- 单链表反转