LeetCode[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.
For example:
Given array A = [2,3,1,1,4]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.)
DP
复杂度
O(N^2), O(1)
思路
每次设置一个窗口,观察在这一步下能到达的最远距离,不断的移动这个窗口。计数,需要移动几次,才能覆盖到末尾的值。
代码
public int jump(int[] nums) {
int cnt = 0, start = 0;
int max = 0, prehigh = 0;
while(max < nums.length - 1) {
cnt ++;
prehigh = max;
for(int i = start; i <= prehigh; i ++) {
max = Math.max(max, nums[i] + i);
}
start = prehigh + 1;
}
return cnt;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。