My readable in place swap solution with Java


  • 0
    A

    Basically I keep 2 indices that both start at 0 index of the array.
    Index i is looking for the first zero encounter and index j is looking for the first non-zero encounter.
    If index j is ahead of index i, swap the value on index i with the value from index j. Otherwise make j the same as i so they both run from the same point

    public void moveZeroes(int[] nums) {
            for (int i = 0, j = 0; j < nums.length && i < nums.length;) {
                if (nums[j] == 0) {
                    j++;
                    continue;
                }
                if (nums[i] != 0) {
                    i++;
                    continue;
                }
                if (i < j) {
                    nums[i] = nums[j];
                    nums[j] = 0;
                } else {
                    j = i;
                }
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.