|
| 1 | +package com.diguage.algo.leetcode; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Arrays; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +public class _0057_InsertInterval { |
| 8 | + // tag::answer[] |
| 9 | + |
| 10 | + /** |
| 11 | + * @author D瓜哥 · https://www.diguage.com |
| 12 | + * @since 2019-10-23 12:27 |
| 13 | + */ |
| 14 | + public int[][] insert(int[][] intervals, int[] newInterval) { |
| 15 | + int left = newInterval[0]; |
| 16 | + int right = newInterval[1]; |
| 17 | + boolean flag = false; |
| 18 | + List<int[]> result = new ArrayList<>(); |
| 19 | + for (int[] ints : intervals) { |
| 20 | + if (right < ints[0]) { |
| 21 | + // 在插入区间的右侧且无交集 |
| 22 | + if (!flag) { |
| 23 | + // 注意:这里是 left, right,不能直接放 newInterval |
| 24 | + result.add(new int[]{left, right}); |
| 25 | + flag = true; |
| 26 | + } |
| 27 | + result.add(ints); |
| 28 | + } else if (ints[1] < left) { |
| 29 | + // 在插入区间的左侧且无交集 |
| 30 | + result.add(ints); |
| 31 | + } else { |
| 32 | + left = Math.min(left, ints[0]); |
| 33 | + right = Math.max(right, ints[1]); |
| 34 | + } |
| 35 | + } |
| 36 | + if (!flag) { |
| 37 | + result.add(new int[]{left, right}); |
| 38 | + } |
| 39 | + return result.toArray(new int[result.size()][2]); |
| 40 | + } |
| 41 | + |
| 42 | + // end::answer[] |
| 43 | + public static void main(String[] args) { |
| 44 | + int[][] result = new _0057_InsertInterval().insert( |
| 45 | + new int[][]{new int[]{1, 2}, new int[]{3, 5}, |
| 46 | + new int[]{6, 7}, new int[]{8, 10}, new int[]{12, 16}}, |
| 47 | + new int[]{4, 8}); |
| 48 | + System.out.println(Arrays.toString(result)); |
| 49 | + } |
| 50 | +} |
0 commit comments