45. Jump Game II
2016-10-31 11:11
274 查看
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
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n<2) return 0;
int level=0,currentMax=0,i=0,nextMax=0;
while(currentMax-i+1>0){
level++;
for(;i<=currentMax;i++){
nextMax=max(nextMax,nums[i]+i);
if(nextMax>=n-1) return level;
}
if(currentMax==nextMax) return INT_MAX;
currentMax=nextMax;
}
return -1;
}
};通过广度优先遍历,统计可以到达的每一个节点可以到达的最远的节点。
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.)
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
if(n<2) return 0;
int level=0,currentMax=0,i=0,nextMax=0;
while(currentMax-i+1>0){
level++;
for(;i<=currentMax;i++){
nextMax=max(nextMax,nums[i]+i);
if(nextMax>=n-1) return level;
}
if(currentMax==nextMax) return INT_MAX;
currentMax=nextMax;
}
return -1;
}
};通过广度优先遍历,统计可以到达的每一个节点可以到达的最远的节点。
相关文章推荐
- leetCode #45 Jump Game II 贪心
- [LeetCode]45 Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- [LeetCode#55, 45]Jump Game, Jump Game II
- LeetCode (45) Jump Game II
- 45. Jump Game II
- 45-Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- LeetCode (45) Jump Game II
- 45. Jump Game II
- leetcode45 Jump Game II
- 45. Jump Game II
- 45. Jump Game II
- LeetCode 45 - Jump Game II
- 45. Jump Game II
- Leetcode45 Jump Game II
- LeetCode 45 Jump Game II
- 45. Jump Game II