LeetCode -- Product of Array Except Self My Submissions Question

Question:

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

Solve it without division and in O(n).

For example, given [1,2,3,4], return [24,12,8,6].

Follow up:
Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)

 Analysis:

给出有n个元素的整数数组(n > 1) nums, 返回一个数组输出,其中output[i]为除了nums[i]外其它个元素的乘积。不要分割数组并且在O(n)的时间内解决这个问题。

例如给出数组:[1, 2, 3, 4],返回[24, 12, 8, 6].

注意:

你能在常数空间复杂度内解决这个问题吗?(在空间复杂度的计算中,output数组不计算在内)

分析:

在计算乘除时,0是一个特殊元素,还要考虑正负号的问题。因此我们的思路是:

a. 一般情况下(无0元素):为避免溢出,用一个long型的参数存储所有元素的乘积,然后循环数组一次,依次除以当前元素的值,将除数保存到output数组中即可;

b. 若数组中含有0元素,但是我们不知道0元素的个数有多少,因此需要用另外一个参数zero对零元素计数。如果数组中仅含一个0,则只有0元素的位置为其他所有元素的乘积,其他的元素都为0;如果数组中含有多余一个0,则所有位置都为0.

本题很简单,只要按照特殊元素0分类即可。

Answer:

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        long temp = 1;
        int zero = 0;
        int[] result = new int[nums.length];
        for(int x : nums) {
                if(x == 0) 
                    zero++;
                else temp *= x;
        }
       
        if(zero > 1)
                return result;
        else if(zero == 1){
                for(int i=0; i<nums.length; i++) {
                    if(nums[i] == 0)
                        result[i] = (int) (temp);
            }
                return result;
        }
        else {
                for(int i=0; i<nums.length; i++) {
                    if(nums[i] == 0)
                        result[i] = (int) (temp / nums[i]);
                    result[i] = (int) (temp / nums[i]);
            }
            return result;
        }
        
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/5201808.html