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.)
然后还需要考虑一个边界的问题,如果当前位置的最远距离已经可以调到数组最后,直接count++,然后return count即可!
class Solution {
public int jump(int[] nums) {int count = 0;//返回值
for(int i = 0;i<nums.length;){//对数组进行遍历
int k = nums[i];
if(i+1<nums.length){//边界控制
int max1 = i+1;
int sum =0;
if(i+k>=nums.length-1){ //当nums[i]的值已经可以一步调到数组末尾,即可直接返回count
count++;
return count;
}
for(int j = i+1;j<=i+k;j++){//对下一个位置的选择
if(j>=nums.length){
count++;
return count;
}
else{
int sum1=j-i+nums[j];
if(sum1>sum){
max1 = j;
sum = sum1;
}
}
}
i = max1;
count++;
}
else{
return count;
}
}
return count;
}
}
另一种解法:
这里只要保证i+A[i]最大即可,for里面的if,是来判断跳到哪一个位置!
class Solution {
public int jump(int[] A) {
int sc = 0;
int e = 0;
int max = 0;
for(int i=0; i<A.length-1; i++) {
max = Math.max(max, i+A[i]);
if( i == e ) {
sc++;
e = max;
}
}
return sc;
}
}