55. Jump Game

栏目: Java · 发布时间: 6年前

内容简介: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.

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.

Example 1:

Input: [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: [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.

难度:medium

题目:给定一非负整数数组,初始位置在数组第一个元素上。每个数组元素的值表示最大能到达的距离。判断是否可以到达数组最好的位置。

思路:计算每个位置所能到达的最大位置,然后取最大值作为最远到达距离。

Runtime: 4 ms, faster than 93.15% of Java online submissions for Jump Game.

Memory Usage: 40.5 MB, less than 0.98% of Java online submissions for Jump Game.

class Solution {
    public boolean canJump(int[] nums) {
        int steps = nums[0];
        for (int i = 0; i <= steps; i++) {
            steps = Math.max(i + nums[i], steps);
            if (steps >= nums.length - 1) {
                return true;
            }
        }
        
        return false;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

程序员的自我修养

程序员的自我修养

俞甲子、石凡、潘爱民 / 电子工业出版社 / 2009-4 / 65.00

这本书主要介绍系统软件的运行机制和原理,涉及在Windows和Linux两个系统平台上,一个应用程序在编译、链接和运行时刻所发生的各种事项,包括:代码指令是如何保存的,库文件如何与应用程序代码静态链接,应用程序如何被装载到内存中并开始运行,动态链接如何实现,C/C++运行库的工作原理,以及操作系统提供的系统服务是如何被调用的。每个技术专题都配备了大量图、表和代码实例,力求将复杂的机制以简洁的形式表......一起来看看 《程序员的自我修养》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具