前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LintCode 跳跃游戏题目分析代码

LintCode 跳跃游戏题目分析代码

作者头像
desperate633
发布2018-08-22 12:16:11
2760
发布2018-08-22 12:16:11
举报
文章被收录于专栏:desperate633desperate633

题目

给出一个非负整数数组,你最初定位在数组的第一个位置。

数组中的每个元素代表你在那个位置可以跳跃的最大长度。

判断你是否能到达数组的最后一个位置。

样例 A = [2,3,1,1,4],返回 true.

A = [3,2,1,0,4],返回 false.

分析

这个问题有两个方法,一个是贪心和 动态规划。

贪心方法时间复杂度为O(N)。

动态规划方法的时间复杂度为为O(n^2)。

代码

代码语言:javascript
复制
public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    public boolean canJump(int[] A) {
        boolean[] can = new boolean[A.length];
        can[0] = true;
        
        for(int i=1;i<A.length;i++) {
            for(int j=0;j<i;j++) {
                if(j+A[j]>=i && can[j]) {
                    can[i] = true;
                    break;
                }
                    
            }
        }
        
        return can[A.length-1];

    }
}
代码语言:javascript
复制
public class Solution {
    /**
     * @param A: A list of integers
     * @return: The boolean answer
     */
    public boolean canJump(int[] A) {
        if(A.length == 0 || A == null)
            return false;
        
        int farthest = A[0];
        
        for(int i=1;i<A.length;i++) {
            if(i+A[i]>farthest && farthest>=i)
                farthest = i+A[i];
        }
        
        return farthest >= A.length-1;

    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.02.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 分析
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档