java - 数组中的不同值

标签 java algorithm recursion

我正在使用 Java,我正在尝试仅使用递归函数而不使用 HashSet ArrayList 等从二维数组中获取所有不同的值, 这些值将仅为 [0-9] 即:

{{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;
    }
}

但这对我没有用,miskate 在哪里?

最佳答案

递归在这里没有多大意义。只需使用一个简单的数组作为存储,并计算不同值的实例,如果您知道范围 (0-9) 那么一个简单的 int[] 就足够了。

这应该可以解决问题:

public static int numOfColors(int[][] map){

    int[] storage = new int[10];

    //iterate through all the values
    for(int i = 0; i<map.length; i++){
        for(int j = 0; j<map[0].length; j++){

            //will throw an Exception if an entry in map is not 0-9
            //you might want to check for that
            storage[map[i][j]]++;

        }
    }

    int colors = 0;
    //now check which values exist.
    for(int i = 0; i<storage.length; i++){
        if(storage[i] != 0) colors++;
    }

    return colors;
}

关于java - 数组中的不同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439671/

相关文章:

list - 无法理解 Haskell 中的原始递归定义

java - 主线程等待

java - JPanel 未显示

Java——如何高效地存储大量String数组

algorithm - 在乘法表中查找不同数字的数量

c - 如何在C中打印带有正确符号的等式

algorithm - 高等数学 - 使用程序求解最优集

algorithm - 以非常规方式反转队列

java - TestContainers、Couchbase 和 Spring Boot - ScheduledFutureTask 被 ScheduledThreadPoolExecutor 拒绝

java - 递归方法如何打印形状