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!
Aucun commentaire:
Enregistrer un commentaire