- Difficulty: Hard
- Related Topics: Array, Greedy
- Link: https://leetcode.com/problems/jump-game-ii/
Description
Given an array of non-negative integers nums
, you are initially positioned at the first index of the array.
给定一非负整数数组 num
,你最初位于数组的 0 下标处。
Each element in the array represents your maximum jump length at that position.
数组里的每一个元素表示你在此处能跳跃的最远距离。
Your goal is to reach the last index in the minimum number of jumps.
你的目标是最少步数内抵达数组的最后一个下标。
You can assume that you can always reach the last index.
你可以假定输入总是合法的(一定能到达最后一个下标)。
Examples
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 <= 3e4
0 <= nums[i] <= 1e5
Solution
由于题目明确说明解一定存在,故只需考虑最远能走多远。初始化两个变量 currentFarthest
表示目前能到达的最远下标,currentEnd
表示当前跳跃的『终点』。遍历每个下标 i
并更新 currentFarthest
,若抵达 currentEnd
,则步数加一,更新『终点』为 currentFarthest
,代码如下:
import kotlin.math.max
class Solution {
fun jump(nums: IntArray): Int {
var result = 0
var currentEnd = 0
var currentFarthest = 0
for (i in 0 until nums.lastIndex) {
currentFarthest = max(currentFarthest, i + nums[i])
if (i == currentEnd) {
result++
currentEnd = currentFarthest
}
}
return result
}
}