卖萌的弱渣

I am stupid, I am hungry.

Product of Array Exclude Itself

Product of Array Exclude Itself

Given an integers array A.

Define B[i] = A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1], calculate B WITHOUT divide operation.

Example

For A = [1, 2, 3], return [6, 3, 2].

Solution

  • Time: O(N2), Space: O(N)
(Product-Of-Array-Exclude-Itself.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
    """
    @param A: Given an integers array A
    @return: An integer array B and B[i]= A[0] * ... * A[i-1] * A[i+1] * ... * A[n-1]
    """
    def productExcludeItself(self, A):
        # write your code here
        B = []
        if A == None or len(A) == 0:
            return B

        for i in range(len(A)):
            sum = 1
            for j in range(len(A)):
                if i != j:
                    sum *= A[j]
            B.append(sum)
        return B