45. Jump Game II
Description
You are given a 0-indexed array of integers nums of length n. You are initially positioned at index 0.
Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at index i, you can jump to any index (i + j) where:
0 <= j <= nums[i]andi + j < n
Return the minimum number of jumps to reach index n - 1. The test cases are generated such that you can reach index n - 1.
Example 1:
- Input: nums = [2,3,1,1,4]
- Output: 2
- Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
- Input: nums = [2,3,0,1,4]
- Output: 2
Constraints:
- 1 <= nums.length <= 104
- 0 <= nums[i] <= 1000
- It’s guaranteed that you can reach
nums[n - 1].
Submitted Code
class Solution:
def jump(self, nums: List[int]) -> int:
n = len(nums)
jumps, curr_end, max_dist = 0, 0, 0
for i in range(n-1):
max_dist = max(max_dist, (i + nums[i])) # 다음 범위에서 갈 수 있는 최대 거리 갱신
if i == curr_end: # 현재 범위를 넘어갈 때 점프 횟수 +1
jumps += 1
curr_end = max_dist
return jumps
Runtime: 3 ms | Beats 88.70%
Memory: 20.11 MB | Beats 49.61%
현재 범위 안에 있는 노드들로 다음 범위에서 갈 수 있는 최대 거리를 계산하는 방법이다.
Other Solutions
1st
class Solution:
def jump(self, nums: List[int]) -> int:
near = far = jumps = 0
while far < len(nums) - 1:
farthest = 0
for i in range(near, far + 1):
farthest = max(farthest, i + nums[i])
near = far + 1
far = farthest
jumps += 1
return jumps
time complexity: 𝑂(𝑛)
space complexity: 𝑂(1)
2nd
class Solution:
def jump(self, nums):
if len(nums) <= 1: return 0
l, r = 0, nums[0]
times = 1
while r < len(nums) - 1:
times += 1
nxt = max(i + nums[i] for i in range(l, r + 1))
l, r = r, nxt
return times