[leetcode]-238. Product of Array Except Self

题目:

Given an array nums of n integers where n > 1,  return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

思路:

Three cases:

  1. more than one 0 in nums, then product for each i is 0
  2. only nums[i] is 0, then res[i] is the production of all other elements, res[0...i-1,i+1...n-1] is 0
  3. no 0 in nums, then res[i] = production of all elements / nums[i]

复杂度:

时间 O(n) ,空间 O(1)

代码:

 public int[] productExceptSelf(int[] nums) {
        int product = 1;
        int zero = 0;
        for(int i = 0; i < nums.length; ++i){
            if(nums[i] == 0){
                zero ++;
            }else {
                product = product * nums[i];
            }
        }
        for(int i = 0; i < nums.length; ++i){
            if(zero >= 2){
                nums[i] = 0;
            }else if(zero == 1){
                if(nums[i] == 0)
                    nums[i] = product;
                else
                    nums[i] = 0;
            }else{
                nums[i] = product/nums[i];
            }
        }
        return nums;
    }

你可能感兴趣的:(算法,leetcode,笔试面试题)