Java>阵列2>零最大 [英] Java > Array-2 > zeroMax

查看:41
本文介绍了Java>阵列2>零最大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码仅遗漏了5个案例,我不知道为什么,有人帮助我。

my code only misses 5 cases and i dont know why, somebody help me.

问题


返回给定数组的版本,其中数组
中的每个零值都替换为
数组中零右边的最大奇数值。如果零的右边没有奇数值,则将
零保留为零。

Return a version of the given array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array. If there is no odd value to the right of the zero, leave the zero as a zero.

zeroMax({0,5,0,3})→{5,5,3,3}

zeroMax({0, 5, 0, 3}) → {5, 5, 3, 3}

zeroMax({0,4,0,3})→{3,4,3,3}

zeroMax({0, 4, 0, 3}) → {3, 4, 3, 3}

zeroMax({0,1,0})→ {1,1,0}

zeroMax({0, 1, 0}) → {1, 1, 0}

我的代码

public int[] zeroMax(int[] nums) {
    int acum = 0;
    int i = 0;
    for( i = 0; i < nums.length;i++){
        if(nums[i]==0){ 
           for(int j = i; j < nums.length;j++){
               if (nums[j]%2!=0){
                acum = nums[j];
                break;
               }
           }
             nums[i]=acum;
        }

    }
    return nums;
}


推荐答案

您缺少的是,您的零的右边可能有多个奇数,您需要选择最大的一个。

What you are missing is, that there could be more than one odd number on the right side of your zero and you need to pick the largest one.

编辑:您还需要重置 acum。我更新了建议:)

And you also need to reset 'acum'. I updated my suggestion :)

这里是一个建议:

public int[] zeroMax(int[] nums) {
    int acum = 0;
    int i = 0;
    for (i = 0; i < nums.length; i++) {
        if (nums[i] == 0) {
            for (int j = i; j < nums.length; j++) {
                if (nums[j] % 2 != 0 && nums[j] > acum) {
                    acum = nums[j];
                }
            }
            nums[i] = acum;
            acum = 0;
        }

    }
    return nums;
}

这篇关于Java&gt;阵列2&gt;零最大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆