Zero to Hero
article thumbnail
Published 2021. 4. 6. 13:48
238. Product of Array Except Self Algorithm
 

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

 

'Algorithm' 카테고리의 다른 글

310. Minimum Height Trees  (0) 2021.04.08
287. Find the Duplicate Number  (0) 2021.04.07
46. Permutations  (0) 2021.04.05
94. Binary Tree Inorder Traversal  (0) 2021.04.05
22. Generate Parentheses  (0) 2021.04.05
profile

Zero to Hero

@Doljae

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!