如何返回未使用空间的数组



这是一条指令:返回一个int数组,其中array[0]是未使用的空格数这是我到目前为止的代码,但我不确定我是否做对了(或者我需要在方法中返回什么(

public int[] counts()
{
int count=0;
for(int i=0; i<array.length;i++)
{
for (int j=0; j<array.length; j++)
{
if (array[i][j] == 0)
{
count = 0;
}
}
}
return;
}

public int[] counts()int[]是返回类型。该方法希望您返回一个一维数组。我从你的问题和代码中了解到,当二维数组中的一个空间是0时,你会想把计数器增加一,但你不是在增加计数器,你只是把它设置为零。你会想改变,

count = 0;

count++; //it's the same as count += 1 or count = count + 1

并将其作为一维数组返回:

return new int[] {count};

您确定正确理解了这个问题吗?如果你返回一个数字(即2D数组中的0(,那么将其作为一个带有单个元素的数组返回实际上没有多大意义。我认为,您被要求做的可能是返回一个数组,该数组中的数字为0,并带有相应的索引。这对我来说更有意义。

如果是这样的话,那么解决方案看起来就像:

int[] getCounts(int[][] array) {
int[] result = new int[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = 0;
for (int val: array[i]) {
if (val == 0)
result[i]++;
}
}
return result;
}

最新更新