Java 1ms O(N) solution


  • 0
    D
    public class Solution {
    public void moveZeroes(int[] nums) {
        int n = nums.length, i=0,j=0;
        while(true){
            for(;i<n && nums[i]!=0;i++); //find next zero
            for(;j<n && nums[j]==0;j++); //find next non-zero
    
            if(i==n || j==n) return;
            
            if(j>i){      // if zero before non-zero then swap it
                int t = nums[i];
                nums[i] = nums[j];
                nums[j] = t;
            }else   j++;  // if zero after non-zero then non-zero is in appropritate place, just increment non-zero index
        }    
    }
    

    }


Log in to reply
 

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