์•Œ๊ณ ๋ฆฌ์ฆ˜๐Ÿฅš/๋ฌธ์ œํ’€์ด (Python)

[LeetCode] 238. product_of_array_except_self (Medium) 2023/5/2

๐Ÿช„ํ•˜๋ฃจ๐Ÿช„ 2023. 5. 2. 23:30
728x90

 

๋ฌธ์ œ ์ œ๋ชฉ ์ •๋‹ต๋ฅ  ๋‚œ์ด๋„
238. product-of-array-except-self 65.1% Medium
 

Product of Array Except Self - LeetCode

Can you solve this real interview question? Product of Array Except Self - Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nu

leetcode.com

 

๋ฌธ์ œ์š”์•ฝ

๋ฐฐ์—ด์˜ ์š”์†Œ ์ค‘ ์ž์‹ ์„ ์ œ์™ธํ•œ ๋‚˜๋จธ์ง€์˜ ๊ณฑ์…ˆ ๊ฒฐ๊ณผ๋ฅผ ๊ฐ€์ง€๋Š” ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์„ ์ถœ๋ ฅํ•˜๋ผ

์กฐ๊ฑด 1) 32๋น„ํŠธ ์ •์ˆ˜ํ˜• ์ˆซ์ž ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง„๋‹ค

์กฐ๊ฑด 2) ๋‚˜๋ˆ—์…ˆ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š๋„๋ก ํ•œ๋‹ค

์กฐ๊ฑด 3) ์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ $ O(n) $ ์ด๋‚ด์—ฌ์•ผ ํ•œ๋‹ค

 

 

์ƒ๊ฐํ–ˆ๋˜ ํ’€์ด 1(์‹œ๊ฐ„์ดˆ๊ณผ) : ์™ผ์ชฝ ๋ฐฐ์—ด, ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด ๋‚˜๋ˆ ์„œ ๊ณฑํ•œ๋‹ค -> ์ƒˆ๋กœ์šด ํ•จ์ˆ˜ ์ •์˜

 

์ƒ๊ฐํ–ˆ๋˜ ํ’€์ด 2 : ์™ผ์ชฝ ๋ฐฐ์—ด, ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด ๋‚˜๋ˆ ์„œ ๊ณฑํ•œ๋‹ค -> for ๊ตฌ๋ฌธ

 

 

ํ’€์ด 1(์‹œ๊ฐ„์ดˆ๊ณผ)

Step1. ๋ฐฐ์—ด์ด ์ฃผ์–ด์ง€๋ฉด ๊ณฑ ์ถœ๋ ฅ -> lambda

 

Step2. ํ•ด๋‹น ์›์†Œ๋ฅผ ์ œ์™ธํ•˜์—ฌ ์™ผ์ชฝ ์˜ค๋ฅธ์ชฝ์œผ๋กœ ๋‚˜๋ˆ„์–ด ๋ฐฐ์—ด ์ „๋‹ฌ -> ์Šฌ๋ผ์ด์‹ฑ ์ด์šฉ

 

 

๊ตฌํ˜„

from functools import reduce
class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        def multiply(arr):
            return reduce(lambda x, y: x * y, arr)

        result=[]
        if len(nums)<=1:
            return []
        if len(nums)==2:
            return nums[::-1]
        for idx in range(0, len(nums)):
            if idx==0:
                result.append(multiply(nums[1:]))
            elif idx==len(nums)-1:
                result.append(multiply(nums[:len(nums)-1]))
            else:
                result.append(multiply(nums[:idx])*multiply(nums[idx+1:]))
        return result

 

 

ํ’€์ด 2  (232ms)

๋ฐ˜๋ณต๋ฌธ์„ ์ด์šฉํ•ด์„œ ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ๊ณฑ์„ ๋‚˜๋ˆ„์–ด ๊ณฑํ•˜๊ธฐ

 

Step1. ์™ผ์ชฝ ๋ฐฐ์—ด์˜ ๊ณฑ์„ ๊ฒฐ๊ณผ์— ์ €์žฅ

 

Step2. ์ €์žฅ๋œ ๊ฒฐ๊ด๊ฐ’์— ์˜ค๋ฅธ์ชฝ ๋ฐฐ์—ด์˜ ๊ฐ’์˜ ๊ณฑ์˜ ๊ฒฐ๊ณผ๋ฅผ ๊ธฐ์กด ๋ฐฐ์—ด์— ๊ณฑํ•œ๋‹ค

 

 

๊ตฌํ˜„ (232ms)

class Solution:     
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        result=[]
        next_left=1
        #์™ผ์ชฝ ์›์†Œ์˜ ๊ณฑ์„ ๊ฒฐ๊ณผ์— ์ถ”๊ฐ€
        for value in nums:
            result.append(next_left)
            next_left*=value
        #์˜ค๋ฅธ์ชฝ๊ฐ’ ๊ณฑ์„ ๊ฒฐ๊ณผ์— ๊ณฑํ•จ    
        next_right=1
        for idx in range(len(nums)-1, -1, -1):
            result[idx]*=next_right
            next_right*=nums[idx]

        return result

 

์˜ˆ์™ธ์ฒ˜๋ฆฌ 1(+15ms)

๋ฐฐ์—ด์˜ ํฌ๊ธฐ๊ฐ€ ๋งค์šฐ ์ž‘์„ ๊ฒฝ์šฐ ๋”ฐ๋กœ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๋ฅผ ํ•ด ๋ณด๋‹ˆ ์˜คํžˆ๋ ค ์ฒ˜๋ฆฌ ์†๋„๊ฐ€ ์ฆ๊ฐ€ํ•˜์˜€๋‹ค.

        if len(nums)<=1:
            return []
        if len(nums)==2:
            return nums[::-1]
728x90