Very easy to understand O(n) Java solution beats 70%


  • 0
    A
    public void moveZeros(int[] nums){
    	if(nums.length == 0 || nums == null) return;
    	int most_left_0 = -1;
    	for(int i = 0; i<nums.length;i++){
    		if(nums[i] == 0){
    			most_left_0 = i;
    			break;
    		}
    	}
    	if(most_left_0 == -1) return;
    			
    	for(int j = most_left_0+1; j<nums.length; j++){
    		if(nums[j] != 0){
    			nums[most_left_0] = nums[j];
    			nums[j] = 0;
    			most_left_0++;
    		}
    	}
    }
    

    The key point is to find the most left 0 in array first, and then start scanning right after that. If there is no 0 in array at all, then return.


Log in to reply
 

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