[LeetCode238]Product of Array Except Self

题目:

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.)

思路:方法1.可以计算出所有元素的乘积product,如果该乘积不为0,则每个元素对应的为product/nums[i];如果为0,则不为0的元素,返回的均为0,为0的元素再遍历计算

方法2.维持两个数组, left[] and right[]. 分别记录 第i个元素 左边相加的和left[i] and  右边相加的和right[i].  那么结果res[i]即为  left[i]+right[i]. follow up 要求O(1)空间. 利用返回的结果数组,先存right数组. 再从左边计算left,同时计算结果值, 这样可以不需要额外的空间. 这种算法比较好

代码1.

public class Solution {
    public int[] ProductExceptSelf(int[] nums) {
        int product = 1;
        for(int i = 0; i < nums.Length; i++)
        {
            product *= nums[i];
        }
        int[] result = new int[nums.Length];
        if(product != 0)
        {
            for(int i = 0; i < nums.Length; i++)
            {
                result[i] = product / nums[i];
            }
        }
        else
        {
            for(int i = 0; i < nums.Length; i++)
            {
                if(nums[i] != 0)
                    result[i] = 0;
                else
                {
                    result[i] = 1;
                    for(int j = 0; j < nums.Length; j++)
                    {
                        if(j != i)
                            result[i] *= nums[j];
                    }
                }
            }
        }
        return result;
    }
}

代码2.

public class Solution {
    public int[] productExceptSelf(int[] nums) {
        int[] res = new int[nums.Length];
        res[res.Length-1] = 1;
        for(int i=nums.Length-2; i>=0; i--) {
            res[i] = res[i+1] * nums[i+1];
        }
        
        int left = 1;
        for(int i=0; i<nums.Length; i++) {
            res[i] *= left;
            left *= nums[i];
        }
        return res;
    }
}
原文地址:https://www.cnblogs.com/zhangbaochong/p/5061601.html