283 move zeros

https://leetcode.com/problems/move-zeroes/description/

class Solution {
    public void moveZeroes(int[] nums) {
        // [0, i) is where the nonzero is
        int i = 0;
        int j = 0;
        int n = nums.length;
        if (n <= 1) {
            return;
        }
        while (j < n) {
            if (nums[j] != 0) {
                swap(nums, i, j);
                //交换并自增之后i一定踩在0上,因为i总是<=j,i所在的位置j要么探过要么正在探索
                //无论如何如果非0一定会触发交换然后i就会往后移动
                i++;
            } 
            j++;
        }
    }
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

看注释

Last updated