标签:out mission ret 方法 ++ lex ota ack war
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.)
Solution1:
Use two vectors to record the product of numbers befor/after the current number.
The result[i] is the product of fwd[i] * bwd[i]
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 int n = nums.size(); 5 vector<int> fwd(n, 1); 6 vector<int> bwd(n, 1); 7 vector<int> res(n); 8 //forward 9 for(int i = 0; i < n - 1; i++){ 10 fwd[i + 1] = fwd[i] * nums[i]; 11 } 12 //backward 13 for(int i = n - 1; i > 0; i--){ 14 bwd[i - 1] = bwd[i] * nums[i]; 15 } 16 for(int i = 0; i < n; i++){ 17 res[i] = fwd[i] * bwd[i]; 18 } 19 return res; 20 } 21 };
Solution 2:
我们可以对上面的方法进行空间上的优化,由于最终的结果都是要乘到结果res中,所以我们可以不用单独的数组来保存乘积,而是直接累积到res中,我们先从前面遍历一遍,将乘积的累积存入res中,然后从后面开始遍历,用到一个临时变量right,初始化为1,然后每次不断累积,最终得到正确结果
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 vector<int> res(nums.size(), 1); 5 for (int i = 1; i < nums.size(); ++i) { 6 res[i] = res[i - 1] * nums[i - 1]; 7 } 8 int right = 1; 9 for (int i = nums.size() - 1; i >= 0; --i) { 10 res[i] *= right; 11 right *= nums[i]; 12 } 13 return res; 14 } 15 };
238. Product of Array Except Self
标签:out mission ret 方法 ++ lex ota ack war
原文地址:http://www.cnblogs.com/93scarlett/p/6362284.html