题目:
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.)
给定一个大小为n的数组,返回的结果数组为除了该元素之外的数组所有元素之积。
思路一:
暴力轮训。超时!
思路二:
维持两个数组,分别保存缺少对应元素之后的其他元素值,之后直接将两个数组相乘即为结果值。
例:
- [1,a1,a1*a2,a1*a2*a3]
- [a2*a3*a4,a3*a4,a4,1]
- 代码:64ms
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int m = nums.size(); vector<int> left(m); vector<int> right(m); left[0] = right[m-1] = 1; for(int i=1; i<m; i++){ left[i] = left[i-1] * nums[i-1]; } for(int i=m-2; i>=0; i--){ right[i] = right[i+1] * nums[i+1]; } for(int i=0; i<m; i++){ nums[i] = left[i] * right[i]; } return nums; } };
思路三:用两个常数替代两个数组,一个从前往后,一个从后往前,因为要做累乘,所以都从第一个元素开始,循环m次。即前元素从头到尾,后元素从尾到头,实现思路二类似的两个数组值重叠相乘。
代码:60ms
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int m = nums.size(); int left = 1; int right = 1; vector<int> result(m, 1); for(int i=0; i<m; i++){ //数组轮训一遍 result[i] *= left; //从数组头到数组尾 left *= nums[i]; result[m-1-i] *= right; //数组尾到数组头 right *= nums[m-1-i]; } return result; } };