๋ฌธ์ ์ ๋ชฉ | ์ ๋ต๋ฅ | ๋์ด๋ |
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]
'์๊ณ ๋ฆฌ์ฆ๐ฅ > ๋ฌธ์ ํ์ด (Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 234. Palindrome_Linked_list (Easy) 2023/5/4 (0) | 2023.05.04 |
---|---|
[LeetCode] 121. Best_Time_to_Buy_and_Sell_Stock (Easy) 2023/5/3 (0) | 2023.05.03 |
[LeetCode] 561. array_partition_i (Easy) 2023/5/2 (0) | 2023.05.02 |
[LeetCode] 15. 3sum (Medium) 2023/5/1 (0) | 2023.05.01 |
[python] 2. ์ฝ๋ฉํ ์คํธ์์ ์ฌ์ฉ๋๋ Python ๊ธฐ๋ณธ (0) | 2023.04.30 |