LeetCode 75

Move Zeroes

Problem
LC 283
Topic
Two Pointers
File
official75_LC283MoveZeroes.java
Path
pkg5leetcode/official75/official75_LC283MoveZeroes.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC283MoveZeroes.java
Approach
Write non-zeroes left; fill rest with zero.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC283MoveZeroes.java
1package pkg5leetcode.official75;2 3/*4 * Move Zeroes | LC 2835 * APPROACH: Write non-zeroes left; fill rest with zero.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC283MoveZeroes {9    static void moveZeroes(int[] nums) {10        int w = 0;11        for (int n : nums) if (n != 0) nums[w++] = n;12        while (w < nums.length) nums[w++] = 0;13    }14 15    public static void main(String[] args) {16        int[] a = {0,1,0,3,12};17        moveZeroes(a);18        check(java.util.Arrays.equals(a, new int[]{1,3,12,0,0}), "case1");19        int[] b = {0};20        moveZeroes(b);21        check(java.util.Arrays.equals(b, new int[]{0}), "case2");22        System.out.println("all tests passed");23    }24 25    static void check(boolean cond, String name) {26        if (!cond) throw new AssertionError("FAILED: " + name);27        System.out.println("  PASS " + name);28    }29}