Skip to content

Commit 738f821

Browse files
committed
[week2] start, solved 1
1 parent b69fc8c commit 738f821

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Blind75 - 4. Product of Array Except Self
3+
https://leetcode.com/problems/product-of-array-except-self/
4+
์กฐ๊ฑด :
5+
- ๋ถ„ํ•  ์—†์ด O(n) ์‹œ๊ฐ„ ๋ณต์žก๋„ ์ดํ•˜๋กœ ํ’€์–ด๋ผ
6+
- nums์˜ ๋ชจ๋“  ์›์†Œ์˜ ๊ณฑ์€ 32๋น„ํŠธ ์ •์ˆ˜ ๋ฒ”์œ„ ๋‚ด์— ๋“ค์–ด์˜จ๋‹ค
7+
- ๋‚˜๋ˆ—์…ˆ ๊ธˆ์ง€
8+
9+
0์ด ๋ช‡๊ฐœ์ธ๊ฐ€?
10+
- 2๊ฐœ ์ด์ƒ : ๋ชจ๋‘ 0์ธ ๋ฐฐ์—ด
11+
- 1๊ฐœ : 0 ๋ณธ์ธ ์ œ์™ธ๋Š” 0์ธ ๋ฐฐ์—ด
12+
- 0๊ฐœ : ์ขŒ ์šฐ ๊ฐ๊ฐ์˜ ๋ฉ”๋ชจ์ด์ œ์ด์…˜์„ ํ•ด์ฃผ๋ฉด O(2n)์œผ๋กœ ๋ฐฐ์—ด ์ƒ์„ฑ, O(n)์œผ๋กœ ์ •๋‹ต ๋ฐฐ์—ด ์ƒ์„ฑํ•˜๋ฏ€๋กœ O(n)
13+
"""
14+
from typing import List
15+
16+
class Solution:
17+
def productExceptSelf(self, nums: List[int]) -> List[int]:
18+
zero_count = nums.count(0)
19+
if zero_count > 1:
20+
return [0] * len(nums)
21+
elif zero_count == 1:
22+
all_product = 1
23+
for num in nums:
24+
all_product *= num if num != 0 else 1
25+
return [0 if num!= 0 else all_product for num in nums]
26+
27+
else:
28+
left_product = [nums[0]]
29+
right_product = [nums[-1]]
30+
for i in range(1,len(nums)):
31+
left_product.append(left_product[i-1]*nums[i])
32+
right_product.append(right_product[i-1]*nums[-1-i])
33+
34+
answer = []
35+
for i in range(len(nums)):
36+
answer.append((left_product[i-1] if i>0 else 1)* (right_product[-1-i] if i < len(nums)-1 else 1))
37+
return answer

0 commit comments

Comments
ย (0)