LeetCode – Move Zeroes (Java)

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 1

public void moveZeroes(int[] nums) {
    int m=-1; 
 
    for(int i=0; i<nums.length; i++){
        if(nums[i]==0){
            if(m==-1 || nums[m]!=0){
                m=i;
            }
        }else{
            if(m!=-1){
                int temp = nums[i];
                nums[i]=nums[m];
                nums[m]=temp;
                m++;
            }
        }
    }
}

Java Solution 2 - Simple

Actually, we can use the similar code that is used to solve Remove Duplicates from Sorted Array I, II, Remove Element. We can use almost identical code to solve those problems!

public void moveZeroes(int[] nums) {
    int i=0;
    int j=0;
 
    while(j<nums.length){
        if(nums[j]==0){
            j++;
        }else{
            nums[i]=nums[j];
            i++;
            j++;
        }
    }
 
    while(i<nums.length){
        nums[i]=0;
        i++;
    }
}
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>
  • Cherry Zhao

    I also found a good analysis here: https://goo.gl/ytZfjO

  • David

    Just reformatting Jangku’s response

  • David


    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++;
    }
    }

  • Jangku

    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++;
    }
    }