LeetCode【#238】Product of Array Except Self

    xiaoxiao2022-07-05  174

    题目链接:

    点击跳转

     

    题目:

    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 numsexcept nums[i].

    Example:

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

    Note: Please solve it without division and in O(n).

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

    题目分析:

    给定一个整型数组,要求输出一个数组,输出数组的第 i 个数为输入数组中除了第 i 个数以外的所有数的乘积。要求:不能使用除法,同时要求是线性的时间复杂度 O(n)。进一步的,能否使用一个常数空间复杂度来解决。

     

    解题思路:

    一开始的思路,求输入数组的所有元素的乘积,然后到了对应的位置,就除对应位置的元素值即可。但该题目要求不能使用除法,而且这种方法在出现有0,或者多个0的时候,会出现问题。

    我们无法使用除法,那就使用乘法,想到要除了该元素的其他元素乘积,那可以先分别求该元素的左边乘积,再求右边乘积,最后两者相乘就是对应结果,用下面例子说明:

    例:1 2 3 4

    求某元素的左边所有元素乘积(边界的认为乘积是1),所以得到

    1 1 2 6 (比如3的左边所有乘积为2).

    求某元素的右边所有元素乘积(边界的认为乘积是1),所以得到(从右到左)

    24 12 4 1

    然后对应位置相乘:

    24 12 8 6

    就是最后结果

    所以本来想着用两个数组分别存储左边元素乘积(顺序下标刚好是 0 1 2 ....)和右边元素乘积(顺序下标反过来的,求的反倒是最后的)。

    但是题目中说到,除了输出数组之外,用常数的额外空间。

    所以我们说的两个数组,就同时用一个输出数组。

    第一步,还是求左边元素乘积,刚好下标是顺序的,所以一个个存进输出数组中。

    第二部,求右边元素乘积,这个时候相当于输出数组要从最后一个往回操作,求出对应右边元素乘积之后,再与输出数组该元素位置的值相乘作为最后的输出值。

     

    AC代码:

    class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> ans; int len = nums.size(); int res = 1; for(int i = 0;i < len;++i) { ans.push_back(res); res *= nums[i]; } res = 1; for(int i = len-1;i>=0;--i) { ans[i] *= res; res *= nums[i]; } return ans; } };

     

    最新回复(0)