前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 题目解析之 Jump Game

Leetcode 题目解析之 Jump Game

原创
作者头像
ruochen
发布2022-01-08 14:56:22
1.2K0
发布2022-01-08 14:56:22
举报

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.

设变量maxStep为当前能够跳跃的最大步数,超过数组长度,就表示能够跳出;否则不能跳出。

那么maxStep怎么求得呢?numsi + i 就代表:从当前位置起跳,所能跳跃的最远位置。

代码语言:txt
复制
    public boolean canJump(int[] nums) {
        if (nums == null || nums.length == 0) {
            return false;
        }
        int maxStep = 0;
        for (int i = 0; i < nums.length; i++) {
            if (maxStep >= nums.length - 1) {
                return true;
            }
            if (nums[i] == 0 && maxStep == i) {
                return false;
            }
            maxStep = Math.max(maxStep, nums[i] + i);
        }
        return true;
    }

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

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