Problem:
Given an int array length 3, if there is a 2 in the array immediately followed by a 3, set the 3 element to 0. Return the changed array.
fix23({1, 2, 3}) → {1, 2, 0}
fix23({2, 3, 5}) → {2, 0, 5}
fix23({1, 2, 1}) → {1, 2, 1}
Solution:
public int[] fix23(int[] nums) { if (nums[0] == 2 && nums[1] == 3) nums[1] = 0; if (nums[1] == 2 && nums[2] == 3) nums[2] = 0; return new int[] {nums[0],nums[1],nums[2]}; }
Well it works, but I think you should just return nums; since problem asks us to return "changed array," right?
ReplyDeletepublic int[] fix23(int[] nums) {
ReplyDeleteif(nums[0]==2 && nums[1]==3){
nums[1]=0;
}
else if(nums[1]==2 && nums[2]==3){
nums[2]=0;
}
return nums;
}
public int[] fix23(int[] nums) {
ReplyDeleteint pointer1 = 0;
for(int pointer2 = 1; pointer2 < nums.length; pointer2++){
if(nums[pointer1] == 2 && nums[pointer2] == 3){
nums[pointer2] = 0;
}
pointer1++;
}
return nums;
}
public int[] fix23(int[] nums) {
ReplyDeletefor(int i=0;i<nums.length-1;i++)
{
if(nums[i] == 2 && nums[i+1] == 3)
{
nums[i+1] = 0;
}
}
return nums;
}