Java solution using two pointers


  • 0
    M

    Here is my solution using two pointers. One to iterate the other one to track the nonzero element.

    public class Solution {
        public void moveZeroes(int[] nums) {
            int nonZeroIndex = 0;
            int ptrIndex = 0;
            while (ptrIndex < nums.length) {
                if (nums[ptrIndex] == 0) {
                    ptrIndex++;
                } else {
                    int tmp = nums[ptrIndex];
                    nums[ptrIndex] = nums[nonZeroIndex];
                    nums[nonZeroIndex] = tmp;
                    nonZeroIndex++;
                    ptrIndex++;
                }
            }
        }
    }

  • 0
    Z

    Two pointers: One points to 0 and the other one iterates.

    public class Solution {
        public void moveZeroes(int[] nums) {
            int zeroIndex = 0;
            while (zeroIndex < nums.length && nums[zeroIndex] != 0) zeroIndex++; //goes to the first zero
            int itrIndex = zeroIndex + 1; //iteration begins after the first zero element
            while (itrIndex < nums.length) {
                if (nums[itrIndex] != 0) nums[zeroIndex++] = nums[itrIndex]; //fills the zero space with the next nonzero element
                itrIndex++;
            }
            while (zeroIndex < nums.length) nums[zeroIndex++] = 0; //fills the last spaces with zeros
        }
    }

Log in to reply
 

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