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 楼答案
可以使用ArrayList而不是数组。这样,在创建数组之前,您不需要知道确切的数字,并且可以跳过计数。 但是,由于不能在Java集合中放置原语,所以需要使用Integer
如果你真的不想使用集合,你仍然可以通过使用enhanced for loop来改进你的代码