[Leetcode]238. Product of Array Except Self

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Leetcode]238. 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.)

 

思路:不能用除法,只能用乘法。对于每个位置,最后的结果是他左边的所有数的积乘上右边所有数的积,

比如,对于 3 这个数, 他这个位置上最后的结果为 8 。8 是左边 [ 1, 2 ] 和 右边 [ 3 ] 的乘积。那么我们可

以先反向遍历数组,得到每个位置上相对应的右边的乘积。先初始化一个结果数组[ 1, 1, 1, 1 ]。执行一次

的结果为 [ 24, 12, 4, 1],再正向遍历一次,得到最后的结果为 [24,12,8,6].

 

 

class Solution {
    public int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] res = new int[n];
        for (int i = 0; i < n; i++)
            res[i] = 1;
        
        int product = 1;
        for (int i = 0; i < n; i++){
            res[i] *= product;
            product *= nums[i];
        }

        product = 1;
        for (int i = n-1; i>=0; i--){
            res[i] *= product;
            product *= nums[i];
        }
        return res;
    }
}

 


以上是关于[Leetcode]238. Product of Array Except Self的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 238. Product of Array Except Self

[LeetCode] 238. Product of Array Except Self

238. [LeetCode] Product of Array Except Self

[LeetCode 238]Product of Array Except Self

[Leetcode]238. Product of Array Except Self

leetcode 238. Product of Array Except Self (Python版)