Studying if/else vs if/if statement
I was trying to write a code where all the 0s will be moved to the right of the array. I just used a left and a right pointer.
public class Solution {
public int[] moveZero(int[] array) {
// Write your solution here
if (array.length==0) {
return array;
}
int left=0;
int right=array.length-1;
while (left<=right) {
if (array[left]!=0) {
left+=1;
}
if (array[right]==0) {
right-=1;
} else {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
left+=1;
right-=1;
}
}
return array;
}
}
I know here I should use the if/else if instead of if/if, that's why I have the index out of the bound error. But I don't understand why? If I have the if/if statement, what's the difference does that make rather than using if/else if in this question?
from Recent Questions - Stack Overflow https://ift.tt/3aZEszF
https://ift.tt/eA8V8J
Comments
Post a Comment