我的github:https://github.com/gaohongbin/leetcode
题目:
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.)
Subscribe to see which companies asked this question
此题跟leetcode55题相似,只是leetcode55让返回的是是否可以到达终点,而这道题让返回的是最少几步可以到达终点。
思路:
设置两个参数,一个first表示正在查找的范围能到哪里,一个sum 表示前一个范围最远能到哪里。
first初始值为nums[0].
参数i用来遍历,参数numOfJum用来记录,现在到达现在i的位置最少需要跳几次。
遍历1到first范围内的所有台阶,看第二次跳跃最远能跳到哪里赋值给sum,当i遍历到first时,修改numOfJum加1,如果sum>=length-1,则表示下次就可以到达终点,此时还需要再判断:如果此时i<=first && first<length-1则numOfJum+1,就是最终的结果。如果此时first>=length-1,则numOfJum 就是最终结果。
如果sum<length-1, 并且i==first 则numOfJum+1,first=sum;循环继续进行。
代码:
public int jump(int[] nums) {
int length=nums.length;
if(length==1)
return 0;
int first=nums[0]; //first代表第一轮能到达的最远处
int sum=nums[0]; //sum代表下一轮能到达的最远处
int numOfJum=1;
int i=1;
while(i<=first){
if(i+nums[i]>sum)
sum=i+nums[i];
if(sum>=length-1){
if(i<=first && first<length-1)
return ++numOfJum;
else
return numOfJum;
}
else if(i==first && first<length-1 ){
first=sum;
numOfJum++;
}
i++;
}
return numOfJum;
}