Java in-place, O(n). Please let me know if this can be improved.


  • 0
    M
    public class Solution {
    public void moveZeroes(int[] nums) {
        //Null Check
        if(nums == null || nums.length == 0){
            return;
        }
        
        int firstZeroIndex = -1;
        //Find Index of First 0
        for(int i=0;i<nums.length-1;i++){
            if(nums[i] == 0)
            {
                firstZeroIndex = i;
                break;
            }
        }
        //If 0 is not found, return
        if(firstZeroIndex <0)
        return;
        //swap the non zero number with the first zero, after swap update the firstzero index
        for(int i= firstZeroIndex; i<= nums.length-1;i++){
            if(nums[i] != 0){
                nums[firstZeroIndex] = nums[i];
                nums[i] = 0;
                firstZeroIndex++;
            }
        }
        
    }
    

    }


Log in to reply
 

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