Jump Game II
今天继续昨天的题目,一道来自LeetCode#45的贪婪算法题,难度为Hard,Acceptance为24.4%。是昨天的Jump Game(回复011查看)的进一步延伸。
题目如下
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 is2
. (Jump1
step from index 0 to 1, then3
steps to the last index.)
解题思路
和Jump Game类似,采用贪婪算法,不同之处在于,这里不仅要求能不能到达最后一个元素,还要求到达的最小移动次数。
按照贪婪的思路,要想移动次数最少,那么每次移动的步长应该最大。
代码如下
java版
public int jump(int[] A) {
int maxReach = A[0];
int edge = 0;
int minstep = 0;
for(int i = 1; i < A.length; i++) {
if (i > edge) {
minstep += 1;
edge = maxReach;
if(edge > A.length - 1)
return minstep;
}
maxReach = Math.max(maxReach, A[i] + i);
if (maxReach == i):
return -1;
}
return minstep;
}
c++版
这里采用了BFS的方法
int jump(int A[], int n) {
if(n<2)return 0;
int level=0,currentMax=0,i=0,nextMax=0;
while(currentMax-i+1>0){ //nodes count of current level>0
level++;
for(;i<=currentMax;i++){ //traverse current level , and update the max reach of next level
nextMax=max(nextMax,A[i]+i);
if(nextMax>=n-1)return level; // if last element is in level+1, then the min jump=level
}
currentMax=nextMax;
}
return 0;
}
关注我
该公众号会每天推送常见面试题,包括解题思路是代码,希望对找工作的同学有所帮助