My Java Solution with Comments


  • 0
    T
    public void moveZeroes(int[] nums) {
        if(nums.length<=0) return;
        // Use a pointer to record indices that do not have 0
        int nonZeroEnd = 0;
        for( int i=0; i<nums.length; i++ ){
            if(nums[i] != 0  ){
                swap(nums,nonZeroEnd,i);
                nonZeroEnd++;
            }
        }
        for( int i=nonZeroEnd; i<nums.length; i++ ){
            nums[i] = 0;
        }
    }
    private void swap(int[] nums, int i, int j){
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

Log in to reply
 

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