友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
45. Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
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.
Example:
Input: [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.
Note:
You can assume that you can always reach the last index.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Runtime: 1 ms, faster than 99.98% of Java online submissions for Jump Game II.
*
* Memory Usage: 36.4 MB, less than 100.00% of Java online submissions for Jump Game II.
*/
public int jump(int[] nums) {
if (Objects.isNull(nums) || nums.length == 0) {
return 0;
}
int step = 0;
int currentStepEnd = 0;
int currentFarthestIndex = 0;
for (int i = 0; i < nums.length - 1; i++) {
currentFarthestIndex = Math.max(currentFarthestIndex, i + nums[i]);
if (i == currentStepEnd) {
step++;
currentStepEnd = currentFarthestIndex;
}
}
return step;
}
// TODO: Dynamic Programming