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>

  1. Jangku on 2016-6-18

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

  2. David on 2016-8-19


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

  3. David on 2016-8-19

    Just reformatting Jangku’s response

  4. Cherry Zhao on 2016-11-17

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

  5. Harmeet Singh on 2017-1-23

    which is wrong

  6. Harmeet Singh on 2017-1-24

    It is wrong. Doesn’t work for trivial cases like 1,0,1

Leave a comment

*