知识点
贪心
解题思路
遍历数组nums,维护一个变量maxReach表示当前能够达到的最远位置。对于每个位置i,如果i超过了maxReach,说明无法到达当前位置,返回false。否则,更新maxReach为max(maxReach, i + nums[i])。当遍历完成后,如果maxReach大于或等于最后一个位置,说明可以到达最后一个障碍,返回true。
Java题解
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return bool布尔型
*/
public boolean can_jump (int[] nums) {
// write code here
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= nums.length - 1) {
return true;
}
}
return false;
}
}



京公网安备 11010502036488号