Algorithm

238. Product of Array Except Self

Doljae 2021. 4. 6. 13:48
 

Product of Array Except Self - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

1. 숫자 기준 왼쪽, 오른쪽 곱배열을 구한 뒤 곱배열을 곱해서 반환

from typing import *


class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        answer = []
        temp1 = [1]
        for i in range(1, len(nums)):
            temp1.append(temp1[-1] * nums[i - 1])
        temp2 = [1]
        for i in range(len(nums) - 1, 0, -1):
            temp2.append(temp2[-1] * nums[i])
        for i in range(len(temp1)):
            answer.append(temp1[i] * temp2[::-1][i])
        return answer

2. 동일한 원리, 최적화

from typing import *


class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        answer = [1]
        for i in range(1, len(nums)):
            answer.append(answer[-1] * nums[i - 1])
        temp = 1
        for i in range(len(nums) - 1, -1, -1):
            answer[i] = answer[i] * temp
            temp *= nums[i]
        return answer