【leetcode刷题笔记】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.


 

题解:注意题目中A[i]代表的是从i能够跳出的最大步数,而不是从i只能跳出A[i]步。

用一个boolean型的数组记录某个位置能够到达。在位置i时,遍历所有的位置j(j<i),如果能够到达j而且能够从j跳到i,那么最终就可以到达i。

代码如下:

 

复制代码
 1 public class Solution {
 2     public boolean canJump(int[] A) {
 3         if(A == null || A.length == 0)
 4             return true;
 5         
 6         boolean[] reach = new boolean[A.length];
 7         reach[0] = true;
 8         
 9         for(int i = 1;i < A.length;i++){
10             for(int j = 0;j < i;j++){
11                 if(reach[j] && j+A[j]>=i){ 
12                     reach[i] = true;
13                     break;
14                 }
15             }
16         }
17         
18         return reach[A.length-1];
19     }
20 }
复制代码
posted @   SunshineAtNoon  阅读(257)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示