티스토리 뷰

안녕하세요. 죠쵸입니다.

오늘의 LeetCode 문제는 238번 Prodcut of Array Except Self 입니다. 난위도는 "Medium" 에 해당합니다.

 

leetcode.com/problems/product-of-array-except-self

 

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

 

#LeetCode 238.Product of Array Except Self(Description)

 

비교적 문제 자체는 이해하기 쉬우나, 조금 생각이 필요한 문제입니다. 주어진 숫자 배열(리스트)로 자신을 제외한 나머지 숫자의 곱을 배열(리스트) 반환하는 문제입니다. 그 이유는 문제의 풀이를 O(n)의 조건으로 풀이하며, 나눗셈을 이용한 풀이방법을 사용하지 않도록 제한이 있기 때문입니다.

 

#LeetCode 238.Product of Array Except Self(Solution)

 

풀이방법은 각 숫자의 기준으로 배열의 왼쪽의 곱셉 리스트를 생성하고, 배열의 오른쪽의 곱셉 리스트를 생성해서 두 리스트를 순차적으로 곱해서 최종값의 리스트를 만들수 있습니다. 오른쪽 곱셈의 리스트를 생성시, 마지막 숫자부터 역순으로 시작하지만 배열에 추가시에는 순서가 거꾸로 될 수 있도록 리스트의 첫번째 인덱스에 반복적으로 Insert 처리 하였습니다. 아래의 코드를 참조 해 주세요.

class Solution:
    def productExceptSelf(self, nums: list) -> list:
        left = []
        right = []
        out = []

        product = 1
        for i in range(0,len(nums)):
            left.append(product)
            product = product * nums[i]

        product = 1
        for i in range(len(nums)-1, -1, -1):
            right.insert(0, product)
            product = product * nums[i]

        for i in range(0, len(nums)):
            out.append(left[i] * right[i])

        return out

 

방문해 주셔서 감사합니다. 여러분의 공감하기(), 댓글과 구독은 저에게 힘이 됩니다.

이상으로 죠쵸였습니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함