Java simple solution 3ms, why just beat 15%? O(n)


  • -1
    L
    public static int[] productExceptSelf(int[] nums){
    		
    		int result = 1;
    		int index = -1;
    		boolean isFirstZero = false;
            int[] output = new int[nums.length];
            
            for(int i=0;i<nums.length;i++){
            	if(nums[i] == 0 && !isFirstZero){
            		isFirstZero = true;
            		index = i;
            		continue;
            	}
            	
            	if(isFirstZero == true && nums[i] == 0){   //the second zero
            		result = 0;
            		break;
            	}
            	else{
            		result *= nums[i];
            	}
            }
            
            if(result == 0){  //have more than one zero
            	return output;
            }
      
            if(index == -1){  //no zero
            	
            	for(int i=0;i<nums.length;i++){
                    
            		output[i] = result/nums[i];
                }
            }else{   //have one zero
            	output[index] = result;
            }
            
            return output;
    	}

  • 1
    K

    It says "solve it without division and in O(n)." You are using division.


Log in to reply
 

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