gpt4 book ai didi

java Codingbat notAlone — 为什么它不适用于这个特定示例

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:06 26 4
gpt4 key购买 nike

We'll say that an element in an array is "alone" if there are values before and after it, and those values are different from it. Return a version of the given array where every instance of the given value which is alone is replaced by whichever value to its left or right is larger.

notAlone([1, 2, 3], 2) → [1, 3, 3]

notAlone([1, 2, 3, 2, 5, 2], 2) → [1, 3, 3, 5, 5, 2]

notAlone([3, 4], 3) → [3, 4]

public int[] notAlone(int[] nums, int val) {
for(int k = 1 ; k<nums.length; k++)
{
if(k!= nums.length-1)
{
int max = nums[k];
if(nums[k-1]>nums[k])
max = nums[k-1];
else if(nums[k+1] > nums[k])
max = nums[k+1];
if(nums[k-1] != nums[k] && nums[k] != nums[k+1])
nums[k] = max;
}
}
return nums;
}

当我在 codingbat 上运行它时,它适用于除此之外的所有示例:notAlone([1, 2, 3, 2, 5, 2], 2) 应该返回 [1, 3, 3, 5, 5, 2],但我的返回 [1, 3, 3, 3, 5, 2] ].

我真的很困惑如何解决这个问题,因为在我看来,我所写的内容也应该适用于这个特定的示例,但显然事实并非如此。我的错误从何而来?我应该如何重写我的代码?非常感谢任何帮助!

最佳答案

你把它复杂化了。如果要替换当前元素,则只需要找到上一个和下一个元素的 max:

public static int[] notAlone(int[] nums, int val) {
for(int k = 1 ; k<nums.length - 1; k++)
{
if(nums[k]==val && nums[k-1] != nums[k] && nums[k] != nums[k+1])
nums[k] = Math.max (nums[k-1], nums[k+1]);
}
return nums;
}

顺便说一句,在您的解决方案中,您忽略了给定值 (val):

Return a version of the given array where every instance of the given value which is alone is replaced...

不过,这不是您的代码在给定情况下失败的原因。您只是没有找到正确的最大值:

k==3时:

int max = nums[k]; // max = 2
if(nums[k-1]>nums[k]) // 3 > 2
max = nums[k-1]; // max = 3
else if(nums[k+1] > nums[k]) // no evaluated. therefore you change num[3] to 3 instead of to 5
max = nums[k+1];

如果您将这 5 行替换为:

int max = nums[k-1];
if(nums[k+1] > max)
max = nums[k+1];

你会得到正确的输出。

关于java Codingbat notAlone — 为什么它不适用于这个特定示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com