Insert Interval leetcode java

愛做飯的小瑩子發表於2014-07-28

題目

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

 

題解:

這道題不僅要insert newInterval同時還要保證能夠merge。那麼就分情況討論。

遍歷每一個已給出的interval,

噹噹前的interval的end小於newInterval的start時,說明新的區間在當前遍歷到的區間的後面,並且沒有重疊,所以res新增當前的interval;

噹噹前的interval的start大於newInterval的end時,說明新的區間比當前遍歷到的區間要前面,並且也沒有重疊,所以把newInterval新增到res裡,並更新newInterval為當前的interval;

噹噹前的interval與newInterval有重疊時,merge interval並更新新的newInterval為merge後的。

 

程式碼如下:

 

 1     public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) {
 2         ArrayList<Interval> res = new ArrayList<Interval>();
 3             
 4         for(Interval each: intervals){
 5             if(each.end < newInterval.start){
 6                 res.add(each);
 7             }else if(each.start > newInterval.end){
 8                 res.add(newInterval);
 9                 newInterval = each;        
10             }else if(each.end >= newInterval.start || each.start <= newInterval.end){
11                 int nstart = Math.min(each.start, newInterval.start);
12                 int nend = Math.max(newInterval.end, each.end);
13                 newInterval = new Interval(nstart, nend);
14             }
15         }
16  
17         res.add(newInterval); 
18  
19         return res;
20     }

 Reference://http://www.programcreek.com/2012/12/leetcode-insert-interval/

 

相關文章