Leetcode#45. Jump Game II
Problem
You are given a 0-indexed array of integers nums
of length n
. You are initially positioned at nums[0]
.
Each element nums[i]
represents the maximum length of a forward jump from index i
. In other words, if you are at nums[i]
, you can jump to any nums[i + j]
where:
0 <= j <= nums[i]
andi + j < n
Return the minimum number of jumps to reach nums[n - 1]
. The test cases are generated such that you can reach nums[n - 1]
.
Example 1:
1 | Input: nums = [2,3,1,1,4] |
Example 2:
1 | Input: nums = [2,3,0,1,4] |
Constraints:
1 <= nums.length <= 10^4
0 <= nums[i] <= 1000
- It’s guaranteed that you can reach
nums[n - 1]
.
Solve
和Jump Game I 不同,沒有到不了的問題
法1
想法蠻簡單的做一個DP,紀錄到達這個節點,最少步數
不需要回頭做
但題目要求要為Greedy algo
1 | class Solution: |
法3 Greedy algo
其實跟法1想法一樣,但更快且Space complexity 更少
不斷更新reach 最遠可以到達的,當到達紀錄的last點時,
再跳躍一次,更新最遠距離,並將count += 1
1 | # 網路的解 |
本部落格所有文章除特別聲明外,均採用 CC BY-NC-SA 4.0 許可協議。轉載請註明來自 Imisky!
評論