热门搜索 :
考研考公
您的当前位置:首页正文

JAVA 二维数组重叠部分合并

来源:东饰资讯网
package com.yaphetzhao.sort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by YaphetZhao on 2017/3/10.
 * 给定一个二维数组,数组的每个元素是一对数,前者小于等于后者,
 * 比如{{1,3}, {3,5}, {1,4}, {6,10}, {10,11}}
 * 合并这些相互有重叠的数组,
 * 输出为{{1,5},{6,11}}
 * <p>
 * int[][] merge(int[][] input) {
 * // your code here
 * }
 */
public class Sort4 {

    public static void main(String[] args) {
        int[][] ints = {{1, 3}, {3, 5}, {1, 4}, {7, 10}, {10, 11}};
        System.out.print(Arrays.deepToString(merge(ints)));
    }

    private static int[][] merge(int[][] input) {
        int maxNum = Integer.MIN_VALUE;
        for (int[] anInput : input)
            maxNum = anInput[0] > anInput[1] ? anInput[0] : anInput[1];
        boolean[] coordinate = new boolean[maxNum + 2];
        for (int[] anInput : input)
            for (int i = anInput[0]; i < anInput[1]; i++)
                coordinate[i + 1] = true;
        List<Integer> list = new ArrayList<>();
        for (int j = 0; j < coordinate.length - 1; j++)
            if (!coordinate[j] && coordinate[j + 1] || coordinate[j] && !coordinate[j + 1])
                list.add(j);
        int[][] output = new int[list.size() / 2][2];
        for (int k = 0; k < output.length; k++) {
            output[k][0] = list.get(k * 2);
            output[k][1] = list.get(k * 2 + 1);
        }
        return output;
    }

}

Top