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 =
The minimum number of jumps to reach the last index is
from index 0 to 1, then
思路:
用一个变量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;
}
}
看过一次解法,这次仍然没能想透彻。。。
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
1step
from index 0 to 1, then
3steps 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;
}
}
看过一次解法,这次仍然没能想透彻。。。
相关文章推荐
- LeetCode(045) Jump Game II (Java)
- leetcode解题之45. Jump Game II&55. Jump Game java (跳跃游戏)
- Jump Game II leetcode java
- Java for LeetCode 045 Jump Game II
- leetcode:Jump Game II 【Java】
- [leetcode-45]Jump Game II(java)
- Jump Game II leetcode java
- [LeetCode][Java] Jump Game II
- [LeetCode][Java] Jump Game II
- [Leetcode] Jump Game II (Java)
- [LeetCode] Jump Game II
- [leetcode]Jump Game II
- leetcode - Jump Game II
- [leetcode] Jump Game II
- LeetCode-Jump Game II
- LeetCode - Jump Game II
- LeetCode_Jump Game II
- [Leetcode 100] 130 Jump Game II
- [Leetcode] Jump Game II
- leetcode: Jump Game II