different way of O(n) time by modifying original array


  • 0
    W
     public int[] productExceptSelf(int[] nums) {
    		int product=1;
    		boolean zeroOdd=false;
    		int cZero=0;
    	        for(int i=0;i<nums.length;i++){
                            //the product of non-zero numbers
    	        	if(nums[i]!=0)	
    	        		product*=nums[i];
    	        	else//count the number of zero  
    	        		cZero++;
    	        }
    	        for(int i=0;i<nums.length;i++){
    	        	if(nums[i]!=0&&cZero==0)
    	        		nums[i]=product/nums[i];
    	        	else if(nums[i]==0&&cZero==1) nums[i]=product;
    	        	else nums[i]=0;
    	        }
    	        return nums;
    	    }
    

Log in to reply
 

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