题目:
给定一个整数数组A。
定义B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], 计算B的时候请不要使用除法。
样例
给出A=[1, 2, 3],返回 B为[6, 3, 2]
解:看样例,B[0]=A[1]*A[2],B[1]=A[0]*A[2],B[2]=A[0]*A[1];
代码中left保存左边的值,
right保存右边的值
class Solution { public: /* * @param nums: Given an integers array A * @return: A long long array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1] */ vector<long long> productExcludeItself(vector<int> &nums) { // write your code here int n = nums.size(),i; vector<long long> left(n, 1); vector<long long> right(n, 1); vector<long long> res(n, 1); for(i = 1; i < n; ++i) left[i] = left[i-1] * nums[i-1]; for(i = n-2; i >= 0; --i) right[i] = right[i+1] * nums[i+1]; for(i = 0; i != nums.size(); ++i) res[i] = left[i] * right[i]; return res; } };