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 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;
    }
}
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>
  • Prashi Dell


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

  • Harmeet Singh

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

  • Harmeet Singh

    which is wrong

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