Java Insert Interval(插入间隔)
来源:互联网 发布:什么是移动数据流量 编辑:程序博客网 时间:2024/05/22 00:06
Problem:
Given a set of non-overlapping & sorted intervals, insert a new interval into the intervals (merge if necessary).
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].
Thoughts of This Problem
Quickly summarize 3 cases. Whenever there is intersection, created a new interval.
Java Solution
/** * 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; }}
0 0
- Java Insert Interval(插入间隔)
- Leetcode #57. Insert Interval 间隔插入 解题报告
- Insert Interval 插入区间
- 插入时间段 Insert Interval
- Insert Interval(区间插入)
- Insert Interval 插入区间
- Insert Interval 插入间隙
- 插入区间Insert Interval
- Insert Interval 插入区间@LeetCode
- [LeetCode] Insert Interval 插入区间
- [Leetcode] Insert Interval (Java)
- Insert Interval (Java)
- [LeetCode][Java] Insert Interval
- [Java]LeetCode57 Insert Interval
- LeetCode | Insert Interval(插入区间)
- Insert Interval 插入区间到多个区间
- LeetCode 57. Insert Interval(插入区间)
- [leetcode-57]Insert Interval(java)
- linux进程状态-TASK_INTERRUPTIBLE and TASK_UNINTERRUPTIBLE
- Android仿新版微信主界面(使用android-support-v7兼容包,兼容2.2及其以上版本)
- AutoLayout(自动布局)入门
- poll和select的使用和差异
- <MFC多线程> 读者写者问题
- Java Insert Interval(插入间隔)
- 2014华为机试题——取出整型数据中出现次数最多的元素,并按照升序排列返回
- java痛苦学习之路[七]---专注移动互联网产品设计研发
- WeChall Training: Crypto - Caesar I
- Linux进程间通信——使用匿名管道
- Android App 内存泄露之Thread
- [ACM] POJ 1936 All in All (查找,一个串是否在另一个串中)
- webcente
- Linux进程间通信——使用命名管道