238. Product of Array Except Self
problem description
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 nums except nums[i].
Example:
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.)
algorithm thought
本来这题最简单的解决办法就是将所有的乘起来,然后每次除一个数,就能得到结果。但是follow up明确静止这么做。为了在O(n)时间做完,还是得先保存一些结果。
定义一个left和一个right数组。保存从最左边和最右边开始,连续数的乘积。将所有的乘积都保存之后,再次遍历数组,就能在O(1)时间算出每个位置应该填的值了。
code
algorithm analysis
时间复杂度O(n),只需要3次遍历数组。空间复杂度O(n),用了两个vector来保存数据。
Last updated