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算法的...后面都是超时了。
看了以下别人的答案才发现思路很简单...
就是先计算当前点(A)能够跳到的最远的节点(B),跳的次数加一,然后计算从A到B之间能够跳到的最远节点(C),然后将B点当作A点,C点作为B点,跳的次数加一,不断计算即可。
由于是别人的代码所以就写转载吧。
public class Solution {
public int jump(int[] nums) {
int sc = 0;
int e = 0;
int max = 0;
for(int i=0; i<nums.length-1; i++) {
max = Math.max(max, i+nums[i]);
if( i == e ) {
sc++;
e = max;
}
}
return sc;
}
}