Skip to content

Commit 2239f2d

Browse files
committed
solve 4
1 parent 2327fc1 commit 2239f2d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

β€Žjump-game/pmjuu.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
'''
2+
μ‹œκ°„ λ³΅μž‘λ„: O(n^2)
3+
- 각 인덱슀 `i`μ—μ„œ μ΅œλŒ€ `nums[i]` λ²”μœ„λ§ŒνΌμ˜ `step`을 νƒμƒ‰ν•˜λ©°, μ΅œμ•…μ˜ 경우 O(n)번의 λ‚΄λΆ€ 연산이 μˆ˜ν–‰λ©λ‹ˆλ‹€.
4+
5+
곡간 λ³΅μž‘λ„: O(n)
6+
'''
7+
8+
class Solution:
9+
def canJump(self, nums: List[int]) -> bool:
10+
n = len(nums)
11+
if n == 1:
12+
return True
13+
14+
dp = [False] * n
15+
dp[-2] = (nums[-2] >= 1)
16+
17+
for i in range(n - 3, -1, -1):
18+
num = nums[i]
19+
can_jump_to_end = (num >= n - i - 1)
20+
if can_jump_to_end:
21+
dp[i] = True
22+
continue
23+
24+
can_jump_through_next_index = any([dp[i + step] for step in range(1, min(num + 1, n))])
25+
dp[i] = can_jump_through_next_index
26+
27+
return dp[0]
28+
29+
30+
'''
31+
μ‹œκ°„ λ³΅μž‘λ„: O(n)
32+
- 배열을 ν•œ 번만 μˆœνšŒν•˜λ©΄μ„œ κ°€μž₯ 멀리 도달할 수 μžˆλŠ” μœ„μΉ˜λ₯Ό κ°±μ‹ ν•˜λ―€λ‘œ O(n)μž…λ‹ˆλ‹€.
33+
34+
곡간 λ³΅μž‘λ„: O(1)
35+
'''
36+
37+
from typing import List
38+
39+
class Solution:
40+
def canJump(self, nums: List[int]) -> bool:
41+
max_reach = 0
42+
n = len(nums)
43+
44+
for i in range(n):
45+
if i > max_reach: # ν˜„μž¬ μΈλ±μŠ€κ°€ 도달 κ°€λŠ₯ν•œ μ΅œλŒ€ λ²”μœ„λ₯Ό λ„˜μ–΄μ„  경우
46+
return False
47+
48+
max_reach = max(max_reach, i + nums[i]) # 도달 κ°€λŠ₯ν•œ μ΅œλŒ€ 거리 κ°±μ‹ 
49+
50+
if max_reach >= n - 1: # λ§ˆμ§€λ§‰ μΈλ±μŠ€μ— 도달 κ°€λŠ₯ν•˜λ©΄ True λ°˜ν™˜
51+
return True
52+
53+
return False

0 commit comments

Comments
Β (0)