LeetCode 57:Insert Interval
2015-06-10 16:42
316 查看
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
Example 2:
Given
This is because the new interval
思路:在list中删除在start和end之间的元素,如果start,或end在某一元素的start和end之间,删除该元素,调整插入元素的start或end值。最后将所需插入的元素插入合适的位置。思想很简单,细节上调了很久,很坑的一题。
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].
思路:在list中删除在start和end之间的元素,如果start,或end在某一元素的start和end之间,删除该元素,调整插入元素的start或end值。最后将所需插入的元素插入合适的位置。思想很简单,细节上调了很久,很坑的一题。
/** * 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> insert(List<Interval> intervals, Interval newInterval) { int n=intervals.size(); int index=0; for(int i=0;i<n;i++){ Interval temp=null; temp=intervals.get(i); if(newInterval.start>=temp.start&&newInterval.end<=temp.end){ return intervals; }else if(newInterval.start>=temp.start&&newInterval.start<=temp.end){ newInterval.start=temp.start; intervals.remove(i); index=i; n--; i--; }else if(temp.start>newInterval.start&&temp.end<newInterval.end){ intervals.remove(i); index=i; n--; i--; }else if(newInterval.end>=temp.start&&newInterval.end<=temp.end){ newInterval.end=temp.end; intervals.remove(i); index=i; n--; i--; } } if(n==0){ intervals.add(newInterval); return intervals; } if(newInterval.end<intervals.get(0).start){ intervals.add(0,newInterval); return intervals; }else if(newInterval.start>intervals.get(n-1).end){ intervals.add(newInterval); return intervals; } for(int j=0;j<n-1;j++){ Interval temp1=intervals.get(j); Interval temp2=intervals.get(j+1); if(temp1.end<newInterval.start&&temp2.start>newInterval.end){ intervals.add(j+1,newInterval); } } return intervals; } }
相关文章推荐
- VirtualBox共享文件夹等高级特性
- Android基础教程(六)之----多选项CheckBox的综合应用
- POJ 1731
- POJ 1734
- POJ 1740
- 通过三个实例初步认识云计算
- JAVA 环境变量
- 各种各样的汽车神总结!简直太精辟了
- C++ Primer Plus 第6版 中文版 清晰有书签PDF+源代码
- 在Solaris 上扩大文件系统
- Solr与HBase架构设计
- 静态成员变量static
- Fix: No hostname when using DHCP in Sun Solaris 8/9/10
- UVA11995:I Can Guess the Data Structure
- C#高级编程第七天----命名空间
- 用HTML5 实现橡皮擦的涂抹效果的教程_html5教程技巧
- jQuery Validation Engine
- POJ 1716
- POJ 1723
- 图片上传裁剪(asp.net)