有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java数组中的不同值

我正在使用Java,我正在尝试只使用递归函数从2d数组中获取所有不同的值,而不使用HashSet ArrayList等。。, 数值将仅为[0-9] i、 e:

{{4,2,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}}; -> Returns 5 (Because 4,2,3,1,0)
{{4,6,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}}; -> Returns 6 (Because 4,2,3,1,0,6)
{{4,4,4,4,4}}; -> Returns 1 (4)

我尝试的是:

public static int numOfColors(int[][] map) {
    int colors = 0;
    if (map == null || map.length == 0) {
        return colors;
    } else {
        int[] subArr = map[map.length - 1];

        for (int i = 0; i < subArr.length; i++) {
            int j = i + 1;
            for (; j < subArr.length; j++) {
                if (subArr[i] == subArr[j]) {
                    break;
                }
            }
            if (j == subArr.length) {
                int k = 0;
                for (; k < map.length - 1; k++) {
                    for (int l = 0; l < map[k].length; l++) {
                        if (subArr[i] == map[k][l]) {
                            continue;
                        }
                    }
                }
                if (k == map.length - 1) {
                    colors++;
                }
            }
        }
        int[][] dest = new int[map.length - 1][];
        System.arraycopy(map, 0, dest, 0, map.length - 1);
        colors += numOfColors(dest);

        return colors;
    }
}

但这对我不起作用,米斯凯特在哪里


共 (1) 个答案

  1. # 1 楼答案

    正如@Cash Lo已经提到的,你需要一些存储空间。所以你可以这样看:

    @Test
    public void numOfColorsTest() {
        int[][] map = new int[][] {{4,2,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}};
        System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
    
        map = new int[][] {{4,6,2,1,4},{4,4,3,1,4},{1,1,4,2,1},{1,4,0,2,2},{4,1,4,1,1}};
        System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
    
        map = new int[][] {{4,4,4,4,4}};
        System.out.println(String.format("numOfColors: %s", numOfColors(map, new int[0], map.length-1)));
    }
    
    public static int numOfColors(int[][] map, int[] collector, int currentPosition) {
        int[] result = collector;
        if (currentPosition < 0) {
            return collector.length;
        }
        for (int color : map[currentPosition]) {
            boolean found = false;
            for (int aResult : result) {
                if (aResult == color) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                int[] newResult = new int[result.length + 1];
                System.arraycopy(result, 0, newResult, 0, result.length);
                newResult[newResult.length - 1] = color;
                result = newResult;
            }
        }
        return numOfColors(map, result, currentPosition-1);
    }