Problem:
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}
Solution:
public int[] notAlone(int[] nums, int val) { for (int i = 0; i < nums.length; i++) { if (i > 0 && i < nums.length-1 && nums[i] == val) { if (nums[i] != nums[i-1] && nums[i] != nums[i+1]) nums[i] = Math.max(nums[i-1], nums[i+1]); } } return nums; }
public int[] notAlone(int[] nums, int val) {
ReplyDeleteint[] newArray = new int[nums.length];
if(nums.length == 0)
return newArray;
if(nums.length == 1)
newArray[0] = nums[0];
for(int i=1; inums[i+1])
nums[i] = nums[i-1];
if(nums[i+1]>nums[i-1] && nums[i] != nums[i-1])
nums[i] = nums[i+1];
}
newArray[i] = nums[i];
}
newArray[0] = nums[0];
newArray[nums.length-1] = nums[nums.length-1];
return newArray;
}
public int[] notAlone(int[] nums, int val) {
ReplyDeleteint[] a = new int[nums.length];
for(int i=1; inums[i+1]){
nums[i] = nums[i-1];
}
else {
nums[i] = nums[i+1];
}
}
}
return nums;
}
code is pasted incorrectly.. can you fix it..
Deletepublic int[] notAlone(int[] nums, int val) {
ReplyDeleteint[] a = new int[nums.length];
for(int i=1; inums[i+1]){
nums[i] = nums[i-1];
}
else {
nums[i] = nums[i+1];
}
}
}
return nums;
}
These are all incorrect.
Delete//THIS IS THE ONLY CORRECT ONE ALL THE OTHER ONES ARE WRONG
ReplyDeletepublic int[] notAlone(int[] nums, int val) {
for (int i = 0; i < nums.length; i++) {
if (i > 0 && i < nums.length-1 && nums[i] == val) {
if (nums[i] != nums[i-1] && nums[i] != nums[i+1])
nums[i] = Math.max(nums[i-1], nums[i+1]);
}
}
return nums;
}
public int[] notAlone(int[] nums, int val) {
ReplyDeletefor(int x=0; x0) && nums[x-1] == nums[x+1]){
return nums;
}
if(nums[x]==val && x>0){
if(nums[x-1]<nums[x+1]){
nums[x] = nums[x+1];
}else nums[x] = nums[x-1];
}
}
return nums;
}
public int[] notAlone(int[] nums, int val) {
ReplyDeletefor(int i = 1;inums[i+1]){
nums[i]=nums[i-1];
}else{
nums[i] = nums[i+1];
}
}
}
}
return nums;
}
public int[] notAlone(int[] nums, int val) {
ReplyDeletefor(int i=0; i < nums.length-1; i++){
if(i>0 && i nums[i-1]){
nums[i]=nums[i+1];
}else if(nums[i+1] < nums[i-1]){
nums[i]=nums[i-1];
}
}
}
}
return nums;
}