|
| 1 | +package hard; |
| 2 | +import java.util.*; |
| 3 | +import classes.Interval; |
| 4 | +import utils.CommonUtils; |
| 5 | + |
| 6 | +/** |
| 7 | + * Created by fishercoder1534 on 10/3/16. |
| 8 | + */ |
| 9 | +public class MergeIntervals { |
| 10 | + |
| 11 | + /**Inspired by this post: https://discuss.leetcode.com/topic/4319/a-simple-java-solution |
| 12 | + * 1. Sort the intervals first, based on their starting point |
| 13 | + * 2. then compare the end point with next interval's start point, if they overlap, then update the end point to the longest one, |
| 14 | + * if they don't overlap, we add it into the result and continue the iteration.*/ |
| 15 | + public static List<Interval> merge(List<Interval> intervals) { |
| 16 | + if(intervals.size() <= 1) return intervals; |
| 17 | + |
| 18 | + Collections.sort(intervals, new Comparator<Interval>() { |
| 19 | + @Override |
| 20 | + public int compare(Interval o1, Interval o2) { |
| 21 | + return o1.start - o2.start; |
| 22 | + } |
| 23 | + }); |
| 24 | + |
| 25 | + List<Interval> result = new ArrayList(); |
| 26 | + for(int i = 0; i < intervals.size(); i++){ |
| 27 | + int start = intervals.get(i).start; |
| 28 | + int end = intervals.get(i).end; |
| 29 | + while(i < intervals.size() && end >= intervals.get(i).start){ |
| 30 | + end = Math.max(end, intervals.get(i).end); |
| 31 | + i++; |
| 32 | + } |
| 33 | + result.add(new Interval(start, end)); |
| 34 | + i--; |
| 35 | + } |
| 36 | + return result; |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String[] args){ |
| 40 | + List<Interval> list = new ArrayList<Interval>(); |
| 41 | +// //test case 1: |
| 42 | +// list.add(new Interval(2,3)); |
| 43 | +// list.add(new Interval(5,5)); |
| 44 | +// list.add(new Interval(2,2)); |
| 45 | +// list.add(new Interval(3,4)); |
| 46 | +// list.add(new Interval(3,4)); |
| 47 | + |
| 48 | + //test case 2: |
| 49 | + list.add(new Interval(1,3)); |
| 50 | + list.add(new Interval(2,6)); |
| 51 | + list.add(new Interval(8,10)); |
| 52 | + list.add(new Interval(15,18)); |
| 53 | + CommonUtils.printList(merge(list)); |
| 54 | + } |
| 55 | + |
| 56 | +} |
0 commit comments