[LC238] Product of Array Except Self

来源:互联网 发布:希腊失业率数据 编辑:程序博客网 时间:2024/06/13 03:45

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

在出现 Solve it without division and in O(n). 之前,我曾经用过的方法是获得所有数字的乘积(除去0),假如存在一个0,那么所有除了0以外的位置结果都将是0,如果有复数个0,那么所有结果都是0.假如不存在0,那么当前位置的乘积就是所有数字的乘积除以当前 num[i]。 但是题目规定我们不能使用除法。

那么我们只能乖乖用乘法了,思考一下最原始的办法该怎么做,对i 位置上的数,我们将其他所有位的数字相乘即为结果。其时间复杂度将会是 O(\(n^2\))。我们是否可以将复杂度降低呢?

思考一下获得乘积的流程:我们需要计算 i 位置之前的数字乘积,乘以 i 位置之后的数字乘积,而且乘积不断累乘,前面的结果乘以 num[i]实际上可以为 i+1 的结果所用。那么方法就很自然获得了。我们使用两次遍历,第一次从左往右,第二次从右往左,i 位置上的数字将会是之前数字的乘积。

在第二轮中,i 位置上的乘积结果将要乘以 i 到数列末尾的乘积结果。
我们使用一个变量 prod 来记录每次的乘积,注意的是在每次赋值以后再乘以当前的数字,这样就能得到除本身以外的结果了

public class Solution {    public int[] productExceptSelf(int[] nums) {        if(nums == null || nums.length == 0){            return nums;        }        int[] res = new int[nums.length];        int prod = 1;        for(int i = 0; i< nums.length; i++){            res[i] = prod;            prod *= nums[i];        }        prod = 1;        for(int i = nums.length - 1; i>= 0; i--){            res[i] *= prod;            prod *= nums[i];        }        return res;    }}
0 0
原创粉丝点击