[LeetCode][JAVA] 283. Move Zeroes

탱귤생귤·2023년 12월 19일
0

LeetCode

목록 보기
9/16

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

I was too obsessed to the two pointers.

class Solution {
    public void moveZeroes(int[] nums) {
        int p1 = 0;
        int p2 = 0; //zero pointer, non-zero pointer
        int n = nums.length;
        //loop until any pointer is at the end
        while (p1 < n && p2 < n) {
            while (nums[p1] != 0 && p1 < n - 1) p1++;
            while ((nums[p2] == 0 || p1 >= p2) && p2 < n - 1) p2++;

            if (nums[p1] == 0 && nums[p2] != 0) {
                int tmp = nums[p1];
                nums[p1] = nums[p2];
                nums[p2] = tmp;

            }
            p1++;
            p2++;
        }
    }
}

I didn’t need to move all pointers.

This is better solution using two pointers.

class Solution {
    public void moveZeroes(int[] nums) {
        int p = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                if (p != i) {
                    int tmp = nums[p];
                    nums[p] = nums[i];
                    nums[i] = tmp;

                }
                p++;
            }
        }
    }
}

This is using arrays of zero like a snowball.

class Solution {
    public void moveZeroes(int[] nums) {
        int snowball = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == 0) {
                snowball++;
            } else if (snowball > 0) {
                int tmp = nums[i];
                nums[i] = nums[i - snowball];
                nums[i - snowball] = tmp;
            }
        }
    }
}

0개의 댓글