有 Java 编程相关的问题?

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

java返回一个矩阵中包含所有负数的数组

我是编程新手,希望养成良好的习惯,我能用另一种更快的方式做到这一点吗

int[] getNegatives(int[][] m) {
    int countNegatives = 0; // used to create length of array
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            if (m[i][j] < 0) {
                countNegatives += 1;
            }
        }
    }
    int[] arr = new int[countNegatives];
    int increase = 0; // used to increment index of array
    for (int i = 0; i < m.length; i++) {
        for (int j = 0; j < m[i].length; j++) {
            if (m[i][j] < 0) {
                arr[increase] = m[i][j];
                increase += 1;
            }
        }
    }
    return arr;
}

共 (1) 个答案

  1. # 1 楼答案

    可以使用ArrayList而不是数组。这样,在创建数组之前,您不需要知道确切的数字,并且可以跳过计数。 但是,由于不能在Java集合中放置原语,所以需要使用Integer

    List<Integer> getNegatives(int[][] m) {
        List<Integer> negatives = new ArrayList<>();
        for (int[] ints : m) {
            for (int anInt : ints) {
                if (anInt < 0) {
                    negatives.add(anInt);
                }
            }
        }
        return negatives;
    }
    

    如果你真的不想使用集合,你仍然可以通过使用enhanced for loop来改进你的代码

    int[] getNegatives(int[][] m) {
        int countNegatives = 0;
        for (int[] ints : m) {
            for (int anInt : ints) {
                if (anInt < 0) {
                    countNegatives += 1;
                }
            }
        }
        int[] arr = new int[countNegatives];
        int increase = 0;
        for (int[] ints : m) {
            for (int anInt : ints) {
                if (anInt < 0) {
                    arr[increase++] = anInt;
                }
            }
        }
        return arr;
    }