30. Insert Interval【LintCode by java】
Description
Given a non-overlapping interval list which is sorted by start point.
Insert a new interval into it, make sure the list is still in order andnon-overlapping
(merge intervals if necessary).
Example
Insert(2, 5)
into[(1,2), (5,9)]
, we get [(1,9)].
Insert(3, 4)
into[(1,2), (5,9)]
, we get[(1,2), (3,4), (5,9)]
.
题意:给定一个区间,将它插进一个有序的区间集合里,新的区间依然要保持有序性。这就需要考虑到区间的合并问题,我们可以定义一个新的集合,来存放最后的结果。定义一个temp游标,用一个循环从旧的集合中依次取出区间,与待插入区间进行比较。那么如何比较呢?假定新区间的end都小于temp的start,那说明新区间比temp要小,那么直接将新区间放进结果集合里就行了,剩下的依次插入。不然,则说明需要进行区间的合并,具体代码如下:
/** * Definition of Interval: * public classs Interval { * int start, end; * Interval(int start, int end) { * this.start = start; * this.end = end; * } * } */ public class Solution { /** * @param intervals: Sorted interval list. * @param newInterval: new interval. * @return: A new interval list. */ public List<Interval> insert(List<Interval> intervals, Interval newInterval) { // write your code here //特殊情况的讨论 List<Interval>ans=new ArrayList<Interval>(); if(intervals.size()==0){ ans.add(newInterval); return ans; } if(newInterval==null){ return intervals; } if(newInterval.start>intervals.get(intervals.size()-1).end){ intervals.add(newInterval); return intervals; } //一般情况的讨论 Interval last=null; for(int i=0;i<intervals.size();i++){ //用不到newIneval Interval temp=intervals.get(i); if(newInterval.start>temp.end){ ans.add(temp); continue; }else{ //分两种情况 if(newInterval.end<temp.start){ ans.add(newInterval); last=temp; }else{ int start=newInterval.start<temp.start?newInterval.start:temp.start; int end=newInterval.end<temp.end?temp.end:newInterval.end; //合并 last=new Interval(start,end); } //对剩下的进行处理 for(int j=i+1;j<intervals.size();j++){ Interval t=intervals.get(j); if(last.end<t.start){ //归并完成 ans.add(last); last=t; }else{ //继续归并 last.end=last.end>t.end?last.end:t.end; } } ans.add(last); break; } } return ans; } }