My simple java O(n) solution


  • 0
    L
        public void moveZeroes(int[] nums) {
            if(nums.length < 1){
    	        return;
            }
            
            int first = 0; int second = 0;
            while(first < nums.length && second < nums.length ){
    	        while(first < nums.length && nums[first] != 0){
    	            first++;
                }
                second = first + 1;
                while(second < nums.length && nums[second] == 0){
    	            second++;
                }
                if(first < nums.length && second < nums.length){
    	            swap(nums, first++ , second++);
                }
            }
    
        }
        
        public void swap(int[] nums, int i, int j){
    	    int tmp = nums[i];
    	    nums[i] = nums[j];
    	    nums[j] = tmp;
        }
    

  • 0
    L

    @leiluo1710 The idea is to find the first zero, and then from that index find the fisrt non-zero, then swap them. So the order will remain the same.


Log in to reply
 

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