您的位置:首页 > 其它

45. Jump Game II

2016-11-17 19:02 453 查看
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.)

Note:

You can assume that you can always reach the last index.

刚开始想用DP,但是要循环判断前面的每一项,复杂度O(n^2),

package l45;

/*
* 分别对到达该处需要的最小step进行求解
*/
public class CopyOfSolution {
public int jump(int[] nums) {
int len = nums.length, cur_min = Integer.MAX_VALUE;
int[] minReach = new int[len];
for(int i=0; i<len; i++)
minReach[i] = Integer.MAX_VALUE;

minReach[0] = 0;
for(int i=1; i<len; i++) {
//if(cur_min >= minReach[i]) break;
for(int j=0; j<i; j++) {
if(nums[j] + j >= i) {
if(minReach[j]!=Integer.MAX_VALUE && minReach[j]+1<minReach[i]) {
minReach[i] = minReach[j]+1;
}
}
}
}

return minReach[len-1];
}
}

考虑到这种解法是:分别对到达该处需要的最小step进行求解,每次都可能会达到末尾,但是不一定是最短的,所以换种perspective考虑,考虑步数一步步增加,并求出最远能到多少,当可以到达末尾,跳出循环即可

*
* 步数一点一点累加,最远能达到最后即可跳出循环
*/
4000

public class Solution {
public int jump(int[] nums) {
int step = 0;
int curMax = 0, preMax = 0, nextMax = 0;
if(nums.length == 1) return 0;

while(true) {
step ++;

for(int i=preMax; i<=curMax; i++) {
if(i+nums[i]>nextMax) nextMax = i+nums[i];
}

if(nextMax >= nums.length-1) return step;

preMax = curMax;
curMax = nextMax;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: