283. Move Zeroes

smart solution

class Solution {
    public void moveZeroes(int[] nums) {
        int zeroIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                if (i > zeroIndex) { // so smart, ๅฆ‚ๆžœๆฒ’ๆœ‰, ๅฐๆ–ผ็ญ‰ๆ–ผ็š„้ƒฝๆœƒ่ฎŠ0
                    nums[zeroIndex] = nums[i];
                    nums[i] = 0;
                }
                zeroIndex++;
            }
        }
    }
}

normal solution

            if (nums[i] != 0) { // ๅฆ‚ๆžœๆ˜ฏ้€™ๆจฃ็š„่ณ‡ๆ–™, Input: [1,0,0,3,12], swap ๅฎŒ, 1้‚„ๆ˜ฏๅŒๅ€‹ไฝ็ฝฎ
                swap(nums, zeroIndex, i);
                zeroIndex++;
            }

Last updated