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].
對於一個n>1的數組,輸出這樣的一個數組:output[i]等於nums中除nums[i]以外所有數的乘積。
Solve it without division and in O(n).
不能使用除法,時間復雜度為O(n).
For example, given [1,2,3,4], return [24,12,8,6].
遍歷數組兩遍,符合時間復雜度O(n),沒有使用額外的空間(額外空間指除了ret之外的空間)。第一遍計算第i個數的左邊部分的乘積,第二遍計算第i個數右邊部分的乘積。
1 class Solution {
2 public:
3 vector<int> productExceptSelf(vector<int>& nums) {
4 if(nums.empty())return vector<int>();
5 int n=nums.size();
6 vector<int> ret(n,1);
7 for(int i=1;i<n;i++){
8 ret[i]=ret[i-1]*nums[i-1];
9 }
10 int right=1;
11 for(int i=n-1;i>=0;i--){
12 ret[i]*=right;
13 right*=nums[i];
14 }
15 return ret;
16 }
17 };