Java solution- avoid useless read/write before meet the first Zero


  • -1
    J
    public void moveZeroes(int[] nums) {
            if(nums==null||nums.length<=0){
                return;
            }
            int begin=0;
            
            while(begin<nums.length&&begin!=0){
                begin++;
            }
            for(int i=begin;i<nums.length;i++){
                if(nums[i]!=0){
                    nums[begin++]=nums[i];
                }           
            }
            for(;begin<nums.length;begin++){
                 nums[begin]=0;
            }
        }

Log in to reply
 

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