DEV Community

Kaitian Xie
Kaitian Xie

Posted on • Edited on

3 1

LeetCode 281. Move Zeros

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay