LeetCode_238_Product of Array Except Self

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]開(kāi)始計(jì)算
        vS2[n-i] = vS2[n-i+1] * nums[n-i];  //由于vS2[n]已知,從vS2[n-1]開(kāi)始計(jì)算
    }   
    for(int i =1; i< n; i++)
    {
        vRst[i] = vS1[i-1] * vS2[i+1];
    }
    return vRst;
}

分析兩個(gè)for循環(huán)可知:

  1. 在第i次循環(huán)時(shí),vS1[i-1]是已知的,且vRst[i]的值不會(huì)對(duì)vS2[i+1]造成影響。

  2. 所以可將vS1[i-1]用一個(gè)int類(lèi)型變量保存,vS2[i+1]的值則保存為vRst[i+1],以滿足題目中不開(kāi)辟額外空間的要求。

給出以下

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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容