Java 返回矩阵中包含所有负数的数组
我是编程新手,希望养成良好的习惯,我能用另一种更快的方式做到这一点吗Java 返回矩阵中包含所有负数的数组,java,arrays,matrix,Java,Arrays,Matrix,我是编程新手,希望养成良好的习惯,我能用另一种更快的方式做到这一点吗 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] &l
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;
}
int[]getNegatives(int[]m){
int countNegatives=0;//用于创建数组长度
对于(int i=0;i
您可以使用数组而不是数组。这样,在创建数组之前,您不需要知道确切的数字,并且可以跳过计数。
但是,您需要使用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;
}
List getNegatives(int[]m){
列表负片=新的ArrayList();
对于(int[]int:m){
for(int-anInt:ints){
if(anInt<0){
否定句。加上(一句话);
}
}
}
返回负片;
}
如果您确实不想使用集合,您仍然可以通过使用
int[]getNegatives(int[]m){
int countNegatives=0;
对于(int[]int:m){
for(int-anInt:ints){
if(anInt<0){
负计数+=1;
}
}
}
int[]arr=新的int[countNegatives];
整数增加=0;
对于(int[]int:m){
for(int-anInt:ints){
if(anInt<0){
arr[增加++]=anInt;
}
}
}
返回arr;
}
您可以使用arraylist,它基本上是一个动态数组,在需要时会增加大小,使用它您只需遍历2d数组一次。也许是回答这个问题的好地方。
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;
}