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.)
題目分析:
給定一個(gè)num數(shù)組瑟由,n>1以故,輸出一個(gè)output數(shù)組,且output[i]等于除num[i]之外所有元素的乘積购对,給出一個(gè)滿足一下條件的solution:
- 不使用除法
- 時(shí)間復(fù)雜度O(n)
- 不使用額外的儲(chǔ)存空間(輸出數(shù)組不算)
解
假定
s1[0] = nums[0];
s2[n] = nums[n];
構(gòu)建以下數(shù)組
s1[i] = nums[0]*nums[1]*nums[i];
s2[i] = nums[n]*nums[n-1]*...*nums[i];
則可知
output[i] =s1[i-1]*s2[i+1]
其中:
s1[i- 1] = nums[0] * nums[1]*...nums[i-1]
s2[i+1] = nums[i+1]* nums[i+2]* ... nums[n]
Solution1
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size()-1;
vector<int> vS1(n+1),vS2(n+1);
vector<int> vRst(n+1);
int result_s = 1,result_e = 1;
for(int i = 1; i<= n; i++)
result_s *= nums[i];
vRst[0] = result_s;
for(int i = 0; i< n; i++)
result_e *= nums[i];
vRst[n] = result_e;
vS1[0] = nums[0];
vS2[n] = nums[n];
for(int i = 1; i<= n; i++)
{
vS1[i] = vS1[i-1] * nums[i]; //由于vS1[0]已知,從vS1[1]開始計(jì)算
vS2[n-i] = vS2[n-i+1] * nums[n-i]; //由于vS2[n]已知,從vS2[n-1]開始計(jì)算
}
for(int i =1; i< n; i++)
{
vRst[i] = vS1[i-1] * vS2[i+1];
}
return vRst;
}
分析兩個(gè)for循環(huán)可知:
在第i次循環(huán)時(shí)欢揖,vS1[i-1]是已知的营罢,且vRst[i]的值不會(huì)對(duì)vS2[i+1]造成影響翼虫。
所以可將vS1[i-1]用一個(gè)int類型變量保存毁涉,vS2[i+1]的值則保存為vRst[i+1],以滿足題目中不開辟額外空間的要求沉帮。
給出以下
Solution2
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size()-1;
vector<int> vRst(n+1);
int result_s = 1;
int s1 = nums[0];
vRst[n] = nums[n];
for(int i= 1; i<=n; i++)
vRst[n-i] = vRst[n-i+1] * nums[n-i];
vRst[0] = vRst[1];
for(int i =1; i<n;i++)
{
vRst[i] = s1 *vRst[i+1];
s1 *= nums[i];
}
vRst[n] = s1;
return vRst;
}
最后是LeetCode Discuss中大犇 給出的答案,比Solution2更快(雖然3個(gè)solution Tn = O(n))
Solution3
vector<int> productExceptSelf(vector<int>& nums) {
int n=nums.size();
int fromBegin=1;
int fromLast=1;
vector<int> res(n,1);
for(int i=0;i<n;i++){
res[i]*=fromBegin;
fromBegin*=nums[i];
res[n-1-i]*=fromLast;
fromLast*=nums[n-1-i];
}
return res;
}