我正在尝试编写一个获取整数数组的代码,检查每个索引的值,如果索引的值为零,则继续下去,直到找到值不为零的索引,然后根据情况更改其值数组中越接近零。例如:
BEFORE ( 0, 1 , 1 , 1 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 0)
AFTER ( 0, 1 , 2 , 2 , 1 , 0 , 1 , 2 , 3 , 2 , 1 , 0)
这是我的代码:
public static void zeroDistance (int [] a)
{
int counterToZero = 0;
int counterToZeroII = 0;
for ( int i = 0; i < a.length; i++ ){
counterToZero = 0;
counterToZeroII = -1;
if ( a[i] != 0 ){
for ( int j = i; a[j] != 0; j++)
{ // From i to the next zero
counterToZero++;
}
for ( int h = i; a[h] != 0 ; h--) // From i to first zero (goes beckwards)
{
counterToZeroII++;
}
if ( counterToZero > counterToZeroII )
a[i] = counterToZero;
else if (counterToZero < counterToZeroII)
a[i] = counterToZeroII;
else if ( counterToZero == counterToZeroII)
a[i] = counterToZero;
}
}
int[] b = a;
for (int h = 0; h < b.length; h++)
System.out.println(b[h] + "/n");
}
这是我得到的输出,我有点不知道问题出在哪里,我仍在查看代码并试图检测我做错了什么,如果你能帮助我并指出问题所在我可能错了,这会很有帮助。另外,如果你知道另一种“排序检查”的方法,比如使用递归,我会非常感激,我正在尝试习惯使用递归,但对我来说仍然很难实现,因此我在时刻。
0/n 2/n 1/n 0/n 5/n 4/n 3/n 3/n 4/n 0/n
最佳答案
我可以向您推荐一种简单的方法。首先从左到右,只考虑最左边的零。然后从右到左,只考虑最接近的右边零。如果之前的距离较小,则将其替换为新的距离。
以下是它的实现方式:
public static void zeroDistance (int [] a) {
// closest == -1 means no zero was found yet
int closest = -1;
for (int i=0 ; i<a.length ; i++)
if (a[i] == 0)
closest = 0;
else {
// short version
// a[i] = closest == -1 ? Integer.MAX_VALUE : ++closest;
// simpler version for your to understand
if (closest == -1)
a[i] = Integer.MAX_VALUE;
else {
closest++;
a[i] = closest;
}
}
closest = -1;
for (int i=a.length-1 ; i>=0 ; i--)
if (a[i] == 0)
closest = 0;
else if (closest != -1 && a[i] > ++closest)
a[i] = closest;
}
示例的输出:
0, 1, 2, 2, 1, 0, 1, 2, 3, 2, 1, 0
关于java - 获取一个数组,判断该数字是否更接近右/左零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757955/