Product of Array Except Self

題目來(lái)源
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è)nums[i],然后還得處理一些特殊情況。

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        long long sum = 1;
        vector<int> res;
        int count0 = 0;
        for (auto num : nums) {
            if (num == 0) {
                count0++;
                continue;
            }
            sum *= num;
        }
        if (count0 > 1)
            return vector<int>(nums.size(), 0);
        for (auto num : nums) {
            if (count0 == 0)
                res.push_back(sum / num);
            else {
                if (num == 0)
                    res.push_back(sum);
                else
                    res.push_back(0);
            }
        }
        return res;
    }
};

感覺(jué)代碼寫的比較亂…然后我還是想的太多,直接乘不好嗎對(duì)吧…代碼如下:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        int n = nums.size();
        vector<int> res(n, 1);
        for (int i=1; i<n; i++) {
            res[i] = res[i-1] * nums[i-1];
        }
        int a = 1;
        for (int i=n-1; i>0; i--) {
            a *= nums[i];
            res[i-1] *= a;
        }
        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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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