題目描述
鏈接:https://leetcode-cn.com/problems/jump-game/
給定一個非負(fù)整數(shù)數(shù)組 nums ,你最初位于數(shù)組的 第一個下標(biāo) 。數(shù)組中的每個元素代表你在該位置可以跳躍的最大長度。判斷你是否能夠到達(dá)最后一個下標(biāo)。
示例
輸入:nums = [2,3,1,1,4]
輸出:true
解釋:可以先跳 1 步,從下標(biāo) 0 到達(dá)下標(biāo) 1, 然后再從下標(biāo) 1 跳 3 步到達(dá)最后一個下標(biāo)。
代碼
// 題解:https://leetcode-cn.com/problems/jump-game/solution/tiao-yue-you-xi-by-leetcode-solution/
public boolean canJump(int[] nums) {
if (nums == null || nums.length <= 1) {
return true;
}
int maxReach = 0;
for (int i = 0; i < nums.length; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
}
return true;
}