贪心
class Solution {
public boolean canJump(int[] nums) {
if (nums.length == 1){
return true;
}
int max= 0;
/**
* 遍历数组,实时更新所能达到的最大距离
* 如果遇到nums[i] == 0,但是最大距离都没有超过i,说明不可能越过这个位置
* 但最后一个位置为0却是可以的,因此遍历到倒数第二个元素就行了
*/
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 0 && max <= i){
return false;
}
max = Math.max(max, i + nums[i]);
/**
* 剪枝,如果已经到达终点就不用循环了
*/
if (max >= nums.length - 1){
return true;
}
}
return true;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(1)
*/
https://leetcode-cn.com/problems/jump-game/