loading...

LeetCode 281. Move Zeros

algobot76 profile image Kaitian Xie Updated on ・1 min read
public void moveZeroes(int[] nums) {
    int count = 0;

    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 0) {
            count++;
            continue;
        }
        if (count > 0) {
            swap(nums, i, i - count);
        }
    }
}

private void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

The essence of this approach is to swap a non-zero element with the left-most zero.

We iterate through the array nums and increment count by one when we encounter a zero, i.e. we calculate the distance between the left-most zero and a non-zero element. Once we meet a non-zero element, we swap it with the zero at i - count. At the end of the iteration, the zeros have been moved to the end and the relative positions of non-zero elements remain unchanged.

Discussion

pic
Editor guide