[LeetCode] Product of Array Expect Self

 

1. ๋ฌธ์ œ : Link

 

2. ํ’€์ด

0์˜ ์œ ๋ฌด์™€ ๊ฐœ์ˆ˜์— ๋”ฐ๋ผ ๋‚˜๋ˆ ์„œ ๊ฐ’์„ ๋„ฃ์–ด์ค€๋‹ค.

์ด ํ•ฉ์—์„œ ๋‚˜๋ˆ„๊ธฐ๋ฅผ ํ•˜๋ฉด O(n)์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ์Œ!

 

3. ์ฝ”๋“œ

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        tmp = 1
        check = 0
        arr = []
        for n in nums:
            if n == 0:
                check += 1
                continue
            else:
                tmp *= n
        if check >= 2:
            for _ in range(len(nums)):
                arr.append(0)
        elif check == 1:
            for n in nums:
                if n == 0:
                    arr.append(tmp)
                else:
                    arr.append(0)
        else:
            for n in nums:
                arr.append(tmp // n)
        return arr
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ