Java O(n) solution in place without basecase.


  • 7
    L
    public class Solution {
        public void moveZeroes(int[] nums) {
            int rightPos = 0, curr = 0;
            while(curr < nums.length) {
                if(nums[curr]!=0) nums[rightPos++] = nums[curr];
                curr++;
            }
            while(rightPos < nums.length) {
                nums[rightPos++] = 0;
            }
        }
    }

  • 0
    W

    It is easy to understand with proper variable names, thanks.


  • 4
    H
    //Idea
    
    public void moveZeroes(int[] nums) {
        int zeroNum      =  0; // the number(length) of zeros
        
     
        for(int i =0 ;i<nums.length;i++){
        	// if nums[i] ==0; zeroNum++;
            if(nums[i]==0){
               zeroNum++;
            }
            // Else nums[i]!=0;
            //        if there are N zeros before it, we should swap the most left zero and nums[i];
            //        else means no zeros if before it, all nozeros until now, just do nothing.
            else{
                if(zeroNum>0){
                    nums[i-zeroNum]= nums[i];
                    nums[i] =0;
                }
            }
            
        }
    }

Log in to reply
 

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