Leetcode ☞ 238. Product of Array Except Self ☆

网址:https://leetcode.com/problems/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.)


我的AC:

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* productExceptSelf(int* nums, int numsSize, int* returnSize) {
    *returnSize = numsSize;//此句不在,输出为空=。=
    int* ans = (int*)malloc(numsSize * sizeof(int));
    ans[0] = ans[numsSize - 1] = 1;
    
    for (int i = 1; i < numsSize; i++){
        ans[i] = ans[i - 1] * nums[i - 1];
    }
    int t = nums[numsSize - 1];
    for (int j = numsSize - 2 ; j >=0 ; j--){
        ans[j] *= t;
        t *= nums[j];
    }
    
    return ans;
}

分析:分别从两边进行乘法。


下为python的╮(╯▽╰)╭,差不离。

class Solution(object):
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        ans = [1] * len(nums)
        left = 1
        for i in range(len(nums)-1):
            left *= nums[i]
            ans[i+1] *= left
        right = 1
        for j in range(len(nums)-1,0,-1):
            right *= nums[j]
            ans[j-1] *= right
        return ans










你可能感兴趣的:(Leetcode ☞ 238. Product of Array Except Self ☆)