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 ofnums
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.)
Analyse: Use a left vector and right vector to record the product until current number from left / right. Space O(n), time O(n).
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 vector<int> left(nums.size(), 1); 5 vector<int> right(nums.size(), 1); 6 7 for(int i = 1; i < nums.size(); i++) 8 left[i] = left[i - 1] * nums[i - 1]; 9 for(int i = nums.size() - 2; i >= 0; i--) 10 right[i] = right[i + 1] * nums[i + 1]; 11 12 vector<int> result(nums.size(), 1); 13 for(int i = 0; i < nums.size(); i++) 14 result[i] = left[i] * right[i]; 15 16 return result; 17 } 18 };
Use the result to store left production and a variable to store the right production. Space O(1), time O(n)
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 int n = nums.size(); 5 vector<int> result(n, 1); 6 7 // first scan nums, and store its left production in result 8 for(int i = 1; i < n; i++) 9 result[i] = result[i - 1] * nums[i - 1]; 10 11 int right = nums[n - 1]; 12 for(int i = n - 2; i >= 0; i--) { 13 result[i] *= right; 14 right *= nums[i]; 15 } 16 return result; 17 } 18 };
时间: 2024-10-21 18:07:27