【问题标题】:Return an array with all negatives in a matrix返回一个矩阵中所有负数的数组
【发布时间】:2020-03-15 22:24:13
【问题描述】:

我是编程新手,想养成良好的习惯,我可以用另一种更快的方式做到这一点吗?

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

【问题讨论】:

  • 您可以使用arraylist,它基本上是一个动态数组,在需要时会增加大小,使用它您只需要遍历二维数组一次。
  • codereview.stackexchange.com 可能更适合回答这个问题。

标签: java arrays matrix


【解决方案1】:

您可以使用ArrayList 代替数组。这样您就不需要在创建数组之前知道确切的数字,并且可以跳过计数。 不过,您需要使用 Integer,因为您不能将原语放入 Java 集合中。

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

如果您真的不想使用 Collections,您仍然可以使用 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;
}

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 1970-01-01
    • 2012-04-14
    • 2019-04-06
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2019-08-08
    相关资源
    最近更新 更多