您的位置:首页 > 其它

【leetcode刷题笔记】Jump Game II

2014-07-21 16:48 387 查看
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.)

题解:跟Jump Game十分相像,把原来的boolean数组改成int型数组,用来记录到达i时候最小的步骤数目,遍历j(j<i),考察从j跳到i需要的步骤数目是否小于当前的reach[i],如果小于,就更新reach[i]。最终返回reach[A.length-1]即可。

代码如下:

public class Solution {
public int jump(int[] A) {
if(A == null || A.length == 0)
return 0;

int[] reach = new int[A.length];
Arrays.fill(reach, Integer.MAX_VALUE);
reach[0] = 0;

for(int i = 1;i < A.length;i++){
for(int j = 0;j < i;j++){
if(reach[j] != Integer.MAX_VALUE && j+A[j]>=i){
reach[i] = Math.min(reach[i], reach[j]+1);
break;
}
}
}

return reach[A.length-1];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: