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]
'''

猜你喜欢

转载自blog.csdn.net/u010801439/article/details/81122652
今日推荐