Can anyone tell me what have I done wrong in this code ?
In this approach, I traverse the array and, as soon as I find a 0 element, I traverse to the right of the 0, and swap it with the 1st non-0 element found.
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i < nums.length;i++) {
if (nums[i]==0) {
for(int j = i+1; j < nums.length;j++) {
if(nums[j]!=0) {
int temp = nums[i];
nums[i]=nums[j];
nums[j]=temp;
}
}
}
}
}
}
For this following input, [0,1,0,3,12]
The expected output is [1,3,12,0,0]
But I am getting [12,3,1,0,0]
Assuming there is no requirement with regard to the ordering, just to keep the original sequence with shifted zeros only you forgot to break the cycle once you have done a shift, so the corresponding method should look like the following:
class Solution {
public void moveZeroes(int[] nums) {
for (int i = 0; i < nums.length;i++) {
if (nums[i]==0) {
for(int j = i+1; j < nums.length;j++) {
if(nums[j]!=0) {
int temp = nums[i];
nums[i]=nums[j];
nums[j]=temp;
break;
}
}
}
}
}
}