Skip to content

Commit b2ffe79

Browse files
committed
feat: add "Product of Array Except Self" solution
1 parent 4d1ba6d commit b2ffe79

File tree

2 files changed

+71
-6
lines changed

2 files changed

+71
-6
lines changed

climbing-stairs/shinsj4653.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
1111
Constraints: 1 <= n <= 45
1212
13-
Time Complexity: O(2^n) ?
13+
Time Complexity: O(2^n)
1414
1515
계단 오르는 방법 중, 중복되지 않는 모든 가지 수 구하기
1616
우선 완탐으로 해보고, 그 다음 최적부분구조 할 수 있는지 체크
@@ -65,6 +65,14 @@
6565
6666
기저조건또 헷갈... n 3 // 2 + 1
6767
68+
하지만, 도식화해보니
69+
결국 dp(n) = dp(n - 1) + dp(n - 2)
70+
71+
1 2
72+
1 1 1 => dp[2] 값
73+
74+
2 1 => 이건 dp[1] 값
75+
6876
Space Complexity: O(n)
6977
dp 배열 n만큼의 크기 지님
7078
Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,71 @@
11
"""
2-
Inputs:
2+
Inputs: 정수형 배열 nums
33
4-
Outputs:
4+
Outputs: 정수형 배열 answer
55
6-
Constraints:
6+
Constraints: 2 <= nums.length <= 10^5
7+
-30 <= nums[i] <= 30
8+
The input is generated such that answer[i] is guaranteed to fit in a 32-bit integer.
79
8-
Time Complexity:
10+
Time Complexity: 반드시 o(n)
911
10-
Space Complexity:
12+
answer의 각 원소는 본인을 제외한 나머지 원소들 곱한 결과
13+
14+
나눗셈 연산도 불가능
15+
사전?
16+
1 2 3 4
17+
2 4 6 8
18+
6 12 18 24
19+
24 48 72 96
20+
21+
dict[0] :
22+
dict[1] :
23+
dict[2] :
24+
dict[3] :
25+
26+
스택?? push, pop 하는데 o(1) 걸림
27+
28+
(1,0) (2,1) (3,2) (4,3)
29+
30+
스택에서 뺀 다음, 다시 넣으면 while st에 갇히지 않나?
31+
32+
# 풀이 본 이후
33+
34+
nums 1 2 3 4
35+
36+
1 1 1 1
37+
38+
1 1 2 6 : 기준 idx 전까지의 곱
39+
40+
24 12 4 1 : 기준 idx 후까지의 곱
41+
42+
=> 더 개선된 풀이: 누적곱을 덮어씌우는 방법
43+
44+
6
45+
24 12 8 6
46+
47+
24
48+
49+
50+
Space Complexity: O(1)
51+
product 배열에 곱 결과를 덮어씌워도 무방
1152
1253
"""
1354

1455

56+
class Solution:
57+
def productExceptSelf(self, nums: List[int]) -> List[int]:
58+
59+
products = [1 for _ in range(len(nums))]
60+
61+
before = 1
62+
for i in range(len(nums) - 1):
63+
before *= nums[i]
64+
products[i + 1] *= before
65+
66+
after = 1
67+
for i in range(len(nums) - 1, 0, -1):
68+
after *= nums[i]
69+
products[i - 1] *= after
70+
71+
return products

0 commit comments

Comments
 (0)