Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Java Solution 2
We can use the similar code that is used to solve Remove Duplicates from Sorted Array I, II, Remove Element.
public void moveZeroes(int[] nums) { int i = 0; int j = 0; while (j < nums.length) { if (nums[j] != 0) { nums[i++] = nums[j]; } j++; } while (i < nums.length) { nums[i++] = 0; } } |
class Solution {
public:
void moveZeroes(vector& nums) {
int lastIndex = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] != 0) nums[lastIndex++] = nums[i];
}
while(lastIndex < nums.size()) nums[lastIndex++] = 0;
}
};
public void moveZeroes(int[] nums) {
int pos = 0;
for(int i=0; i<nums.length; i++){
if(nums[i] != 0){
nums[pos]= nums[i];
pos++;
}
}
for(int i=pos; i<nums.length; i++){
nums[i] = 0;
}
}
It is wrong. Doesn’t work for trivial cases like 1,0,1
which is wrong
I also found a good analysis here: https://goo.gl/ytZfjO
Just reformatting Jangku’s response
public void moveZeros(int[] arr) {
if (arr.length < 2) return;
int j = 0;
int i = 1;
while (i < arr.length) {
if (arr[i] != 0 && arr[j] == 0) {
arr[j++] = arr[i];
arr[i] = 0;
}
i++;
}
}
public void moveZeros(int[] arr) {
if (arr.length < 2) return;
int j = 0;
int i = 1;
while (i < arr.length) {
if (arr[i] != 0 && arr[j] == 0) {
arr[j++] = arr[i];
arr[i] = 0;
}
i++;
}
}