move all zeros to the end

 class Solution {

    public void moveZeroes(int[] nums) {
       int i=0;
       for(int j=0; j<nums.length; j++){
        if(nums[j]!=0){
            nums[i]=nums[j];
            i++;
        }
       }
       while(i<nums.length){
        nums[i]=0;
        i++;
       }
    }
}


//using two pointer appraoch
int j=-1;
        for(int i=0; i<nums.length; i++){
            if(nums[i]==0){
                j=i;
                break;
            }
        }
        if(j==-1) return;

        //swapping with non zero elements
        for(int i=j+1; i<nums.length; i++){
            if(nums[i]!=0){
                int temp=nums[i];
                nums[i]=nums[j];
                nums[j]=temp;
                j++;
            }
        }
        return;

Comments

Popular Posts