简体   繁体   中英

java Codingbat notAlone — why doesn't it work for this specific example

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;
}

When I ran this on codingbat, it worked for all examples except for this: notAlone([1, 2, 3, 2, 5, 2], 2) should return[1, 3, 3, 5, 5, 2], but instead mine returned[1, 3, 3, 3, 5, 2].

I am really stuck on how to solve this, because in my mind, what I've written should work for this specific example as well, but apparently it doesn't. Where does my error come from? How should I re-write my code? Any help would really be appreciated!

You're over complicating it. You only need to find the max of the previous and next elements if the current element should be replaced:

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;
}

BTW, in your solution you ignore the given value ( val ):

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

That's not the reason why your code failed in the given case, though. You simply didn't find the correct maximum:

When 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];

If you replaced these 5 lines with:

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

you would have gotten the correct output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM