温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Can't spot a the problem in my code for array assortment in Java

其他 - 在我的Java数组分类代码中找不到问题

发布于 2020-03-27 15:56:07

所以我有一个赋值,我需要将数组中的所有1都变成距最接近的0的距离。因此,当我运行它时,输出中的最后一个数字将保持为1,而应将其更改为2。可以有人帮我发现我的错误吗?

基本上,zeroDistance的作用是将数组传递一次,更改所有值,然后从后面开始运行,然后再次更改它们。

    public static void zeroDistance (int [] a)
{
    int counter = 0;
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == 0)
            counter = 0;
        if (a[i] == 1)
        {
            counter++;
            a[i] = counter;
        }
    }
    counter = 0;
    for (int i = a.length - 1; i >= 0; i--)
    {
        if (a[i] == 0)
            counter = 0;
        if (a[i] != 0)
        {
            counter++;
            if (a[i] > counter)
                a[i] = counter;
        }
    }
}

输入:

int[] a={0,1,1,1,1,1,1,0,1,1,1,1,1,0,1,1};

输出:

zeroDistance method result : 
0, 1, 2, 3, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 1
Should return : 
0, 1, 2, 3, 3, 2, 1, 0, 1, 2, 3, 2, 1, 0, 1, 2

查看更多

查看更多

提问者
Froggy
被浏览
15
Philippe B. 2020-01-31 18:59

Your problem comes from the second loop. Since you start over from the end of the array, your second loop considers that you have encountered a 0 at the end of your array, which is obviously not the case here.

So according to your code in your second loop if (a[i] > counter) will be true, since a[1] is 2 and counter is 1 in your first iteration, that leading to your last member of your array being 1 in your result.

As other people said. Don't change values before you encounter a zero. Don't assume that the end of your array is a 0. If you want to fix your problem you can set counter = a[a.length - 1]; before your second loop. But that is not very sexy, I think you can come up with another approach for your problem.

Hope this helps.

EDIT

正如罗比指出的那样。如果您开头有一个1,则在第一个循环中也会遇到问题。

话虽如此,这似乎是对我有利的版本。不要犹豫指出任何错误。

public static void zeroDistance (int[] a)
{
    List<Integer> zerosCoordinates = new ArrayList<>();

    for (int i = 0; i < a.length; i++) {

        if (a[i] == 0)
            zerosCoordinates.add(i);
    }

    for(int i : zerosCoordinates) {

        for (int j = i - 1, k = 1; j >= 0; j--, k++) {

            if (a[j] == 0)
                break;

            if (a[j] != 0 && a[j] < k)
                a[j] = k;
        }
    }

    for (int i : zerosCoordinates) {

        for (int j = i + 1, k = 1; j < a.length; j++, k++) {

            if (a[j] == 0)
                break;

            if (a[j] != 0 && a[j] > k || j == a.length - 1)
                a[j] = k;
        }
    }

    for (int i = 0; i < a.length; i++)
        System.out.print(a[i]);
}

当然有更好的方法可以做到这一点。为此我很着急。

发布
问题

分享
好友

手机
浏览

扫码手机浏览