LeetCode 238. 有个方法hin nice
class Solution(object): def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ 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
思路:
first time going through the array, it's beginning to the end. p keeps a running total of the product, and each element will equal the running total of the products of the elements that came before. then the 2nd time going through the array, you're doing the same process, but backwards, finishing off the result by multiplying the elements that came after.
example: [1,2,3,4]. let's say initially, your output is [1, 1, 1, 1] and p = 1.
Loop 1:
i = 0, your output becomes [1*1, 1, 1, 1] and p = p * 1 (1)
i = 1, your output becomes [1, 1*1, 1, 1] and p = p * 2 (2)
i = 2, your output becomes [1, 1, 1*2, 1] and p = p * 3 (6)
i = 3, your output becomes [1, 1, 2, 6]
Loop 2 (p = 1 again)
i = 3, your output becomes [1, 1, 2, 6*1] and p = p * 4 (4)
i = 2, your output becomes [1, 1, 2*4, 6] and p = p * 3 (12)
i = 1, your output becomes [1, 1*12, 8, 6] and p = p * 2 (24)
final result: [24, 12, 8, 6]
有点难懂,还没消化。。