您的位置:首页 > 编程语言 > Java开发

LeetCode 第四十五题(Jump Game II)Java

2016-11-08 20:35 357 查看
原题:

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.)
思路:

用一个变量curRch记录下当前步数最远能走到哪里;

用一个变量curMax依次遍历,得到以某一位置下能到达的最远位置;

如果遍历到 i 位置,curRch到达不了的话,说明此时要多走一步到 i 位置,并更新curRch;

记录步数并返回;

代码:public class Solution {
public int jump(int[] nums) {
int Length=nums.length;
int times=0;
int curRch=0;
int curMax=0;
for(int i=0;i<Length;i++){
if(curRch<i){
times++;
curRch=curMax;
}
curMax=Math.max(curMax,nums[i]+i);
}
return times;
}
}

看过一次解法,这次仍然没能想透彻。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: