Leetcode 第238題:Product of Array Except Self--除自身以外數組的乘積(C++、Python)

題目地址:Product of Array Except Self


題目簡介:

給定長度爲N的整數數組nums,其中N>1,返回輸出數組output,其中output[i]等於nums中除nums[i]之外其餘各元素的乘積。

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]

Note: Please solve it without division and in O(n).

進階:在常數空間複雜度內完成這個題目嗎?


題目解析:

原始 1 2 3 4
左側開始 - 1 1*2 1*2*3
右側開始 2*3*4 3*4 4 -

把上表中,下側兩行想乘便是結果。

C++版:

class Solution {
public:
    vector<int> productExceptSelf(vector<int>& nums) {
        vector<int> ans(nums.size(), 1);
        for (int i = 1; i < nums.size(); i++)
            ans[i] = ans[i - 1] * nums[i - 1];
        int temp = 1;
        for (int j = nums.size() - 2; j >= 0; j--)
        {
            temp *= nums[j + 1];
            ans[j] *= temp;
        }
        return ans;
    }
};

Python版:

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        ans = [1 for i in range(len(nums))]
        for i in range(1, len(nums)):
            ans[i] = ans[i - 1] * nums[i - 1]
        temp = 1
        for j in range(len(nums) - 2, -1,-1):
            temp *= nums[j + 1]
            ans[j] *= temp
        return ans

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章