Simple Java solution


  • 12
    L
        int zeroCount = 0;
        for(int i = 0 ; i< nums.length; i++) {
            if (nums[i] == 0) {
                zeroCount++;
            } else if (zeroCount > 0 ){
                nums[i-zeroCount] = nums[i];
                nums[i] = 0;
            }
        }

  • 0
    H

    Great solution!Thanks


  • 0
    L

    public void moveZeroes(int[] nums) {

            int step=0;	
            for(int i=0;i<nums.length-1;i++){
            	if(nums[i]==0&&nums[i+1]!=0){
            	    //switch of 0 and non-zero
            		nums[i-step]=nums[i+1];
            		nums[i+1]=0;	        		
            	}else if(nums[i]==0&&nums[i+1]==0){
            		step++;//Number of steps
            	}
            }
        
    }

Log in to reply
 

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