Java - 5 Lines - E A S Y


  • 0
    J

    -Shift all non-zero numbers to the left replacing all zero positions.
    -Keep count of all the zeros on the way.
    -Place zeros in the back of the array.

    public class Solution {
        public void moveZeroes(int[] nums) {
            int currentIndex = 0, zeroCount = 0;
            for(int i = 0; i < nums.length; i++) {
                if(nums[i] != 0) nums[currentIndex++] = nums[i];
                if(nums[i] == 0) zeroCount++;
            }
            for(int i = nums.length-zeroCount; i < nums.length; i++) nums[i] = 0;
        }
    }
    

Log in to reply
 

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