[Leetcode-java] 56. Merge Intervals:计算重叠数组

一、问题链接:

https://leetcode.com/problems/merge-intervals/

  • 问题是针对提出的二维数组,去掉交叉的部分,计算出部分重叠的数组
  • 变更点:之前传入的参数为list对象,此次改成了二维数组

二、思路:

1、先对二维数组中的一维数组左端(类似于线段的起点开始排序)
2、根据排序后的数组的值,按顺序遍历遍历数组元素,结合最后合并成功的元素来融合
3、合并的情况如下所示:

before current final case
[1,4] [3,8] [1,8] 相邻合并中if,需要移除上一个数组,重新写入
[1,8] [3,4] [1,8] 相邻合并中 else if,需要判断的数组已经包含在内了,此时不需要进行处理,外部的for循环保证正常的数组遍历即可
[1,8] [10,15] [1,8],[10,15] 没有交叉,正常写入即可

三、编码

class Solution {
    public int[][] merge(int[][] intervals) {
        int start = 0;
        int end = 1;
        int bound = 2;

        if (intervals.length < bound) {
            return intervals;
        }

        //二维数组排序
        for (int i = 0; i < intervals.length; i++) {
            int[] currentI = intervals[i];
            for (int j = i + 1; j < intervals.length; j++) {
                int[] currentJ = intervals[j];
                if (currentI[start] > currentJ[start]) {
                    swap(currentI, currentJ);
                }
            }
        }
        List list = new ArrayList();
        list.add(intervals[0]);
        //相邻合并
        for (int i = 0; i < intervals.length; i++) {
            int[] temp = new int[intervals[i].length];
            int[] currentI = intervals[i];
            int[] before = list.get(list.size() - 1);

            if (before[end] >= currentI[start] && before[end] <= currentI[end]) {
                temp[start] = before[start];
                temp[end] = currentI[end];
                list.remove(before);
                list.add(temp);
            } else if (before[end] >= currentI[start] && before[end] > currentI[end]) {
              //need do nothing
            } else {
                list.add(currentI);
            }
        }

        int[][] result = new int[list.size()][];
        int index = 0;
        for (int[] temp : list) {
            result[index++] = temp;
        }
        return result;

    }

    public static void swap(int[] currentI, int[] currentJ) {
        int[] swap = new int[currentI.length];
        System.arraycopy(currentI, 0, swap, 0, currentI.length);
        System.arraycopy(currentJ, 0, currentI, 0, currentI.length);
        System.arraycopy(swap, 0, currentJ, 0, currentJ.length);
    }

}

你可能感兴趣的:([Leetcode-java] 56. Merge Intervals:计算重叠数组)