Ques: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.
Ans:
public int[] notAlone(int[] nums, int val) {
int swap = 0;
for (int i = 0; i < nums.length-1; i++) {
if ((nums[i] == val&&i!=0)&&(nums[i] == val&&i!=nums.length-1)){
//check the vale before and after it
if ((nums[i-1] > nums[i + 1])) {
nums[i] = nums[i - 1];
} else if (nums[i-1] < nums[i + 1]) {
nums[i] = nums[i + 1];
}
}
}
return nums;
}
Ans:
public int[] notAlone(int[] nums, int val) {
int swap = 0;
for (int i = 0; i < nums.length-1; i++) {
if ((nums[i] == val&&i!=0)&&(nums[i] == val&&i!=nums.length-1)){
//check the vale before and after it
if ((nums[i-1] > nums[i + 1])) {
nums[i] = nums[i - 1];
} else if (nums[i-1] < nums[i + 1]) {
nums[i] = nums[i + 1];
}
}
}
return nums;
}
No comments:
Post a Comment