一個長度為 n 的整形數組nums
,其中 n > 1,返回一個數組 output
,其中 output[i]
等於nums
中除nums[i]
以外所有元素的乘積。
不用除法 且在O(n)內解決這個問題。
例如,輸入 [1,2,3,4]
,返回 [24,12,8,6]
。
進階:
你可以在常數空間復雜度內解決這個問題嗎?(注意:出於空間復雜度分析的目的,輸出數組不被視為額外空間。)
解題思路:
- 用兩個數組left,right來保存從左到右的乘積,和從右到左的乘積
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 int len = nums.size(); 5 int *left = new int[len], *right = new int [len]; 6 left[0] = nums[0]; right[len-1] = nums[len-1]; 7 for(int i = 1; i < len-1; i++) { 8 left[i] = left[i-1]*nums[i]; 9 right[len-i-1] = right[len-i]*nums[len-i-1]; 10 } 11 vector<int> ans; 12 ans.push_back(right[1]); 13 for(int i = 1; i < len-1; i++) ans.push_back(left[i-1]*right[i+1]); 14 ans.push_back(left[len-2]); 15 return ans; 16 } 17 };