156. Merge Intervals【LintCode by java】
Description
Given a collection of intervals, merge all overlapping intervals.
Example
Given intervals => merged intervals:
[ [
(1, 3), (1, 6),
(2, 6), => (8, 10),
(8, 10), (15, 18)
(15, 18) ]
]
Challenge
O(n log n) time and O(1) extra space.
題意:給定一個集合,裏面有若幹無序區間,要求將有重疊部分的區間合並。這個題目的示例給的不是很好,這個示例給人的感覺好像這些區間是有序的。有序和無序,用同樣的方法做,結果可能不一樣,比如我一開始理解成有序,報錯如下:
Input
[(2,3),(4,5),(6,7),(8,9),(1,10)]
Output
[(2,3),(4,5),(6,7),(1,10)]
Expected
[(1,10)]
Hint
Review your code and make sure your algorithm is correct. Wrong answer usually caused by typos if your algorithm is correct.
Input test data (one parameter per line.)
雖然它本來無序,但我們也可以人為地將它根據first值的大小進行排序,可以使用Collections類中的sort方法(查一下API)對List進行排序。排完之後,就可以對集合內的區間進行合並了。合並的方法與此題類似:30. Insert Interval【LintCode by java】
申請一個新的集合,再用一個循環,將排好序的區間兩兩比較,如果無需合並,則將前者加入新的集合,後者繼續與後面的區間比較合並。代碼如下:
1 public class Solution {
2 /**
3 * @param intervals: interval list.
4 * @return: A new interval list.
5 */
6 //判斷兩區間是否相交
7 public List<Interval> merge(List<Interval> intervals) {
8 // write your code here
9 if(intervals.size()==0||intervals.size()==1)
10 return intervals;
11 List<Interval>res=new ArrayList<Interval>();
12 Collections.sort(intervals,new IntervalCompare());
13 Interval last=intervals.get(0);
14 for(int i=1;i<intervals.size();i++){
15 Interval cur=intervals.get(i);
16 if(last.end<cur.start){
17 res.add(last);
18 last=cur;
19 }else{
20 last.start=Math.min(last.start,cur.start);
21 last.end=Math.max(last.end,cur.end);
22 }
23 }
24 res.add(last);
25 return res;
26 }
27 private class IntervalCompare implements Comparator<Interval>{
28 public int compare(Interval a,Interval b){
29 return a.start-b.start;
30 }
31 }
32 }
如有錯誤,歡迎批評指正~
156. Merge Intervals【LintCode by java】