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.
Determine if you are able to reach the last index.
Example 1:
Input: [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
给一个数组,每个元素是能走的最大步数,问从index 0开始走的话能否到达终点,
和45题类似,但是45题要求给出具体步数,先写55,再写45
思路:
greedy
初始位置在index=0处,这是最开始我们能到达的地方,用canReach=0表示,
然后从0出发,往后面走,沿途不断更新能到达的地方,canReach = i + nums[i].
如果canReach >= n-1就说明能到达最后的index,直接返回true.
反之,如果遍历完了也不能到达最后的index,返回false.
45题只需要在 i==curEnd的条件里count++就行了
public boolean canJump(int[] nums) {
int n = nums.length;
int canReach = 0;
for(int i = 0; i <= canReach; i++) {
int nextDest = i + nums[i];
if(nextDest >= n-1) return true;
canReach = Math.max(canReach, nextDest);
}
return false;
}
45题代码
public int jump(int[] nums) {
int cnt = 0;
int n = nums.length;
int canReach = 0;
int curMax = 0;
for(int i = 0; i <= canReach; i++) {
if(i == n-1) return cnt;
canReach = Math.max(canReach, i+nums[i]);
if(i == curMax) {
cnt ++;
curMax = canReach;
}
}
return cnt;
}