55. Jump Game

You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

 

Example 1:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

 

public boolean canJump(int[] nums) {
int maxLocation = 0;
for (int i = 0; i < nums.length; i++) {
if (maxLocation < i)
return false; //如果上一个maxLocation 小于i,说明到不了这个地方。例如当前位置index是4,但是之前最多能到3,所以到不了4处,更到不了结尾处
maxLocation = Math.max(i + nums[i], maxLocation); //看这个位置最多能到什么地方(即i + nums[i]),如果大于当前maxLocation ,就更新maxLocation
}
return true;
}
posted @   MarkLeeBYR  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
点击右上角即可分享
微信分享提示