|
| 1 | +/** |
| 2 | + * Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary). |
| 3 | + * |
| 4 | + * You may assume that the intervals were initially sorted according to their start times. |
| 5 | + * |
| 6 | + * Example 1: |
| 7 | + * Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9]. |
| 8 | + * |
| 9 | + * Example 2: |
| 10 | + * Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16]. |
| 11 | + * |
| 12 | + * This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10]. |
| 13 | + */ |
| 14 | + |
| 15 | +import java.util.ArrayList; |
| 16 | +import java.util.Arrays; |
| 17 | +import java.util.Comparator; |
| 18 | + |
| 19 | +public class InsertInterval { |
| 20 | + public class IntervalCmp implements Comparator<Interval> { |
| 21 | + |
| 22 | + @Override |
| 23 | + public int compare(Interval i1, Interval i2) { |
| 24 | + if (i1.start < i2.start) { |
| 25 | + return -1; |
| 26 | + } |
| 27 | + if (i1.start == i2.start && i1.end <= i2.end) { |
| 28 | + return -1; |
| 29 | + } |
| 30 | + return 1; |
| 31 | + } |
| 32 | + |
| 33 | + } |
| 34 | + |
| 35 | + public ArrayList<Interval> insert(ArrayList<Interval> intervals, |
| 36 | + Interval newInterval) { |
| 37 | + intervals.add(newInterval); |
| 38 | + Interval[] arr = new Interval[intervals.size()]; |
| 39 | + intervals.toArray(arr); |
| 40 | + Arrays.sort(arr, new IntervalCmp()); |
| 41 | + intervals.clear(); |
| 42 | + int start = arr[0].start; |
| 43 | + int end = arr[0].end; |
| 44 | + for (int i = 1; i < arr.length; i++) { |
| 45 | + if (arr[i].start <= end) { |
| 46 | + end = Math.max(end, arr[i].end); |
| 47 | + } else { |
| 48 | + intervals.add(new Interval(start, end)); |
| 49 | + start = arr[i].start; |
| 50 | + end = arr[i].end; |
| 51 | + } |
| 52 | + } |
| 53 | + intervals.add(new Interval(start, end)); |
| 54 | + return intervals; |
| 55 | + } |
| 56 | +} |
0 commit comments