0

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12] Output: [1,3,12,0,0] Example 2:

Input: nums = [0] Output: [0]

Constraints:

1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1

My Solution:-

public class MoveZeros {
    public void moveZeroes(int[] nums) {

        List<Integer> li = new ArrayList<Integer>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                li.add(nums[i]);
            }
        }
        while (nums.length > li.size()) {
            li.add(0);
        }
        for (int i = 0; i < li.size(); i++)
            nums[i] = li.get(i);
    }

    public static void main(String[] args) {
        int num[] = { 0, 1, 0, 3, 12 };
        MoveZeros move = new MoveZeros();
        move.moveZeroes(num);
        System.out.println(Arrays.toString(num));
    }
}

Any other way we can solve this problem?

5
  • 3
    If your solution is already working you may have better luck on codereview.stackexchange.com but be sure to read their rules before posting there Commented Jul 2 at 13:43
  • 4
    Additionally, this solution is not in place. According to your instructions, you cannot create a new ArrayList and append items to it.
    – Andrew Yim
    Commented Jul 2 at 13:43
  • If a question is related to a problem that has a web page, such as a programming practice / challenge web site, it is polite to include a link to that page. Is this the correct link? leetcode.com/problems/move-zeroes/description Commented Jul 2 at 14:23
  • You could do that in place by modifying the code for a bubble sort. But, a bubble sort runs in O (n^2). The followup asks if you can do it in less. Commented Jul 2 at 14:30
  • 1
    There are planty of ways. You may sort the array using a stable sorting algorithm fitted to consider 0 greater than non-zero and everything else equal. You may move non-zero to the left (whjich can in turn be done in more than one way) and and fill out with zeroes.
    – Anonymous
    Commented Jul 2 at 16:04

2 Answers 2

6

We can do this without moving the zeros:

  • We keep track of the number of positions that we have non-zero elements (using if (num != 0)). Simultaneously, we move the non-zero elements to the beginning of the nums array.
  • Then, we set all elements after the pos count to zero.
import java.util.Arrays;

public class MoveZeros {
    public static void moveZeroes(int[] nums) {
        if (nums == null || nums.length == 0)
            return;

        int pos = 0;
        for (int num : nums) {
            if (num != 0) {
                nums[pos++] = num;
            }
        }
        while (pos < nums.length) {
            nums[pos++] = 0;
        }
    }

    public static void main(String[] args) {
        int[] nums = { 0, 1, 0, 3, 12 };
        MoveZeros.moveZeroes(nums);
        System.out.println(nums == null ? "null" : Arrays.toString(nums));
    }
}

Prints

[1, 3, 12, 0, 0]

Comments:

  • BTW, static methods should be invoked using the class name, not via an instance. – WJS
2
  • 1
    BTW, static methods should be invoked using the class name, not via an instance.
    – WJS
    Commented Jul 2 at 14:59
  • We can directly define static method no need Instance name moveZeroes(nums); Thank you Commented Jul 5 at 6:34
1

Here is my method for your reference.

If the element i of array is 0, left shift the array and put 0 to the last (calculate --n to avoid checking the 0s again). If the element i of array is not 0, then check the next one, i.e. i + 1.

public class MoveZeros {
    public void moveZeroes(int[] nums) {
        int i = 0, n = nums.length;
        while(i < n)
            if (nums[i] == 0) {
                for (int j = i + 1; j < n; j++)
                    nums[j - 1] = nums[j];
                nums[--n] = 0;
            } else {
                i++;
            }
    }
    
    public static void main(String[] args) {
        int num[] = { 0, 1, 0, 3, 12 };
        MoveZeros move = new MoveZeros();
        move.moveZeroes(num);
        System.out.println(Arrays.toString(num));
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.