238. Product of Array Except Self

Doyeon Kim·2022년 8월 5일

코딩테스트 공부

목록 보기
99/171

문제 링크 : https://leetcode.com/problems/product-of-array-except-self/


해당 배열을 제외한 나머지 배열들을 곱한 값들을 반환하는 문제이다.

해당 문제를 풀 수 있는 방법(원리)중에 하나로 prefix(앞에서부터) 와 postfix(뒤에서부터)를 (추상적으로) 만들고 ->해당배열<- 에 넣어주면 되는 것이다..


class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        ans = [1] * len(nums)
        
        pre = 1
        for i in range(len(nums)):
            ans[i] = pre
            pre *= nums[i]
        post = 1
        for i in range(len(nums)-1,-1,-1):
            ans[i] *= post
            #그냥 res = post로 저장하면 오버라이딩 됨
            post *= nums[i]
        return ans

22.09.28
복습완

profile
성장하고 도전하는 개발자. 프로그래밍 좋아하세요?

0개의 댓글