leetcode 238. Product of Array Except Self

题目:

题目分析:

本题输入一个列表,[1,2,3,4],输出为【24,12,8,6】,即每一个输入元素,对应输出时为,除此元素以外的其他元素的乘积。

代码分析:

1.输入为列表,输出为列表

2.考虑到输出元素为除当前元素以外的元素的乘积,故需要考虑前后

3 .方式1 :利用for 循环,i之前进行乘积,在对i之后进行乘积,最后,将两值相乘得出最后结果。

 程序代码:

#version 1 

class Solution:
    def productExceptSelf(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        s = []
        for i in range(len(nums)):
            total1 = 1
            total2 = 1
            for w in range(i):                        # i 左边进行相乘
                total1 = total1 * nums[w]
            for j in range(i + 1, len(nums)):         # i 右边相乘
                total2 = total2 * nums[j]
            total = total1 * total2                   # i 左右两边相乘
            s.append(total)                           # 将i对应的结果增加到列表s当中
        return s
#version 2
class Solution:
    # @param {integer[]} nums
    # @return {integer[]}
    def productExceptSelf(self, nums):
        p = 1
        n = len(nums)
        output = []
        for i in range(0,n):            #从左往右乘
            output.append(p)
            p = p * nums[i]
        p = 1
        for i in range(n-1,-1,-1):      #从右往左乘
            output[i] = output[i] * p
            p = p * nums[i]
        return output


'''
解析:
The idea is that for each element of the array, you would want to multiply all 
the elements to the left and right. So in the first for loop you are cumulatively
 multiplying all the previous elements to each other in each iteration, essentially 
multiplying all the elements to the left of the element. In the second for loop, you
 will be doing the same now except now in reverse as you will be multiplying all the
 elements to the right.

[1, 2, 3, 4] <---- input
[1]
[1, 1]
[1, 1, 2]
[1, 1, 2, 6]

[1, 1, 2, 6] *note that the last element of the array is already its answer because 
it is the product of all the elements to the left of it
[1, 1, 8, 6]
[1, 12, 8, 6]
[24, 12, 8, 6]
'''

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Will-kkc

您的鼓励将成为我继续写作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值