Merge Intervals
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18]
,
return [1,6],[8,10],[15,18]
.
复用 Insert Interval代码即可。
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 ArrayList<Interval> merge(ArrayList<Interval> intervals) { 12 // Note: The Solution object is instantiated only once and is reused by each test case. 13 ArrayList<Interval> results = new ArrayList<Interval>(); 14 if(intervals == null || intervals.size() == 0) return intervals; 15 for(int i = 0; i < intervals.size(); i ++) 16 { 17 results = insert(results,intervals.get(i)); 18 } 19 return results; 20 } 21 22 public ArrayList<Interval> insert(ArrayList<Interval> intervals, Interval newInterval) { 23 // Note: The Solution object is instantiated only once and is reused by each test case. 24 ArrayList<Interval> results = new ArrayList<Interval>(); 25 boolean sig = false; 26 for(int i = 0; i < intervals.size(); i ++) 27 { 28 if(intervals.get(i).start > newInterval.end) 29 { 30 if(!sig) 31 { 32 results.add(newInterval); 33 sig = true; 34 } 35 results.add(intervals.get(i)); 36 } 37 else 38 { 39 newInterval.end = Math.max(newInterval.end, intervals.get(i).end); 40 } 41 if(intervals.get(i).end < newInterval.start) 42 { 43 results.add(intervals.get(i)); 44 } 45 else 46 { 47 newInterval.start = Math.min(newInterval.start, intervals.get(i).start); 48 } 49 } 50 if(!sig) 51 { 52 results.add(newInterval); 53 } 54 return results; 55 } 56 }
第二遍:
1 public class Solution { 2 public ArrayList<Interval> merge(ArrayList<Interval> intervals) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 ArrayList<Interval> result = new ArrayList<Interval>(); 5 if(intervals == null || intervals.size() == 0)return result; 6 PriorityQueue<Interval> pq = new PriorityQueue<Interval>(intervals.size(), new Comparator<Interval>(){ 7 public int compare(Interval a, Interval b){ 8 return a.start > b.start ? 1 : (a.start == b.start ? 0 : -1); 9 } 10 }); 11 for(Interval interval:intervals){ 12 pq.add(interval); 13 } 14 result.add(pq.poll());//poll out the minimum element in the queue 15 int max_end = result.get(0).end; 16 while(pq.size() != 0){ 17 Interval tmp = pq.poll(); 18 if(tmp.start <= max_end){ 19 max_end = max_end > tmp.end ? max_end : tmp.end; 20 result.get(result.size() - 1).end = max_end; 21 }else{ 22 result.add(tmp); 23 max_end = tmp.end; 24 } 25 } 26 return result; 27 } 28 }
先把interval 按start time 排序,再添加。 保存当前的最大end time。
posted on 2013-10-04 08:04 Step-BY-Step 阅读(242) 评论(0) 编辑 收藏 举报