File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
product-of-array-except-self Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 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
You canโt perform that action at this time.
0 commit comments