[Java] O(n) time and O(1) space, deal with zero object


  • -1
    S

    There are 3 cases:

    1. Include more than 2 "Zero" -> All output are zero.

    2. Include one "Zero" -> Expect the zero object is product, others are 0.

    3. Not include "Zero" -> Each output is product / itself

          int zeroCount = 0;
          int product = 1;
      
          // Get product and zero count.
          for (int i : nums) {
              if (i != 0) {
                  product *= i;
              } else {
                  zeroCount++;
                  if (zeroCount >= 2) break;
              }
          }
      
          int[] output = new int[nums.length];
      
          if (zeroCount >= 2) {
              // All output are zero.
          } else if (zeroCount == 1) {
              for (int i = 0; i < nums.length; i++) {
                  output[i] = nums[i] == 0 ? product : 0;
              }
          } else {
              for (int i = 0; i < nums.length; i++) {
                  output[i] = product / nums[i];
              }
          }
      
          return output;

  • 0
    C

    Doesn't this violate the stipulation in the problem setup that division not be used?


  • 0
    S

    Yes, I don't notice this rule.


Log in to reply
 

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