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

标签 java arrays loops for-loop if-statement

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/

相关文章:

javascript - Angular2 应用优化

Scala - 每个循环之间的区别

java - 菜单中的嵌套循环

multithreading - OpenMP 5.1 规范是否允许使用非矩形循环的折叠子句?

java - 使用 Google Guava API 进行过滤

java - 来自 Jersey 2.x 的过多警告消息

java - 在通知中使用 ConstraintLayout 时崩溃

java - 使用外部属性运行 Jar 文件

python - 3D 数组中一个轴上的滚动平均值

c# - 将 WHERE sql 子句拆分为数组