Jump Game
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.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
题解:
给定一个数组,从第一个元素开始,元素的值表示能够往后跳的最大距离,问这样一个数组能否跳到最后一个元素。
思路:使用传说中的贪心算法 全局最优解等效于局部最优解 这题自己理解是 算出前面的最大值 即当前的位置加上能跳的最大步数 如果出现当前的位置i大于最大步数 表示false 不能到达最后的值
public class Solution {
public boolean canJump(int[] nums) {
int max = 0;
for(int i = 0; i < nums.length; i++){
if(i > max) return false;
max = Math.max(i + nums[i] , max); //能跳的最大步数
}
return true;
}
}