Leetcode-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]
.
Anaylsis:
Method 1: Sort the start points and end points respectively. For the ith point, if the (i-1)th end point is smaller than the ith start point, then the previous i-1 intervals are merged to one interval.
Method 2: Count the delta value at each time point. start: +1, end:-1. Then starting from the first time point, if the accumulative value reaches 0, then we get one interval.
Solution 1
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> merge(List<Interval> intervals) { 12 List<Interval> res = new ArrayList<Interval>(); 13 if (intervals.size()==0) return res; 14 if (intervals.size()==1){ 15 res.add(intervals.get(0)); 16 return res; 17 } 18 19 20 List<Integer> sList = new ArrayList<Integer>(); 21 List<Integer> eList = new ArrayList<Integer>(); 22 for (int i=0;i<intervals.size();i++){ 23 sList.add(intervals.get(i).start); 24 eList.add(intervals.get(i).end); 25 } 26 Collections.sort(sList); 27 Collections.sort(eList); 28 29 int p1=0; 30 while (p1<sList.size()){ 31 int p2 = p1+1; 32 while (p2<sList.size() && sList.get(p2)<=eList.get(p2-1)) p2++; 33 Interval inter = new Interval(sList.get(p1),eList.get(p2-1)); 34 res.add(inter); 35 p1 = p2; 36 } 37 38 return res; 39 } 40 }
Solution 2:
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> merge(List<Interval> intervals) { 12 Map<Integer,Integer> pMap = new HashMap<Integer,Integer>(); 13 List<Integer> pList = new ArrayList<Integer>(); 14 15 //Count the delta at each point. 16 for (int i=0;i<intervals.size();i++){ 17 Interval cur = intervals.get(i); 18 if (pMap.containsKey(cur.start)){ 19 pMap.put(cur.start,pMap.get(cur.start)+1); 20 } else { 21 pList.add(cur.start); 22 pMap.put(cur.start,1); 23 } 24 if (pMap.containsKey(cur.end)){ 25 pMap.put(cur.end,pMap.get(cur.end)-1); 26 } else { 27 pList.add(cur.end); 28 pMap.put(cur.end,-1); 29 } 30 } 31 32 //Now, sort the time points. 33 Collections.sort(pList); 34 35 //Now construct new interval list. 36 List<Interval> res = new ArrayList<Interval>(); 37 int index1 = 0; 38 while (index1<pList.size()){ 39 int val = pMap.get(pList.get(index1)); 40 int index2 = index1; 41 while (val!=0){ 42 index2++; 43 val += pMap.get(pList.get(index2)); 44 } 45 Interval one = new Interval(pList.get(index1),pList.get(index2)); 46 res.add(one); 47 index1 = index2+1; 48 } 49 return res; 50 } 51 }
The most important thing here is to consider that the intervals are not sorted!.