leetcode : 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].
给一个长度大于 1 的数组,给出另外一个数组,使得给出的数组没一项 a[i] 是原来的数组中除了第 i 个元素之外其他所有元素的积
乍一看求个积全部乘起来然后一个个除就可以了,但是这样必须考虑有 0 的情况,而且题目也要求了不能用除法。
仔细想想这个题其实是会想到 动态规划 和 线段树的。
最后比较好理解又简单的方法是动态规划:
分别求出每个位置左边的元素的积和右边的积,然后撑起来就可以了,左边的积可以存在要返回的数组里,右边的积由于只要用一次,所以保存在一个变量里一直更新就好了。
这里即使可以用除法也不能将左边的积用一个int 来保存,因为来个0就全丢了。
AC 代码:
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { vector<int> leftProduct(nums.size(), 1); for (int i = 1; i < nums.size(); ++i) { leftProduct[i] = leftProduct[i - 1] * nums[i - 1]; } int rightProduct = 1; for (int i = nums.size() - 2; i >=0; --i) { rightProduct *= nums[i + 1]; leftProduct[i] *= rightProduct; } return leftProduct; } };
浙公网安备 33010602011771号