[Leetcode] Insert Interval

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].

 

Solution:

- -这道题提交了好多次才通过的。。。

遍历每一个已给出的interval,

当当前的interval的end小于newInterval的start时,说明新的区间在当前遍历到的区间的后面,并且没有重叠,所以res添加当前的interval;

否则:

当当前的interval的start小于newInterval的end时,说明新的区间与当前遍历到的区间重叠,所以merge interval并更新新的newInterval为merge后的。

直到两个区间没有重叠,res添加newInterval. (注意啊,注意,是这个时候讲新的newInterval加入到res中)

这时候再判断用于遍历的i有没有到达intervals的终点,如果没有,说明有interval在newInterval的后边儿,没有重叠,将它加入到res即可。

 1 /**
 2  * Definition for an interval.
 3  * public class Interval {
 4  *     int start;
 5  *     int end;
 6  *     Interval() { start = 0; end = 0; }
 7  *     Interval(int s, int e) { start = s; end = e; }
 8  * }
 9  */
10 public class Solution {
11     public List<Interval> insert(List<Interval> intervals, Interval newInterval) {
12         List<Interval> res=new ArrayList<Interval>();
13         if(intervals==null||intervals.size()==0){
14             res.add(newInterval);
15             return res;
16         }
17         int i=0;
18         while(i<intervals.size()&&(intervals.get(i).end<newInterval.start)){
19             res.add(intervals.get(i++));
20         }
21         while(i<intervals.size()&&(intervals.get(i).start<=newInterval.end)){
22             newInterval.start=Math.min(newInterval.start,intervals.get(i).start);
23             newInterval.end=Math.max(newInterval.end,intervals.get(i).end);
24             i++;
25         }
26         res.add(newInterval);
27         while(i<intervals.size())    
28             res.add(intervals.get(i++));
29         return res;
30     }
31 }

 

posted @ 2015-02-01 02:17  Phoebe815  阅读(150)  评论(0编辑  收藏  举报