LeetCode刷题笔录Jump Game

来源:互联网 发布:sentinel1数据下载 编辑:程序博客网 时间:2024/06/07 13:14

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.



用动态规划来做,jump[i]表示在i位置剩余的最大步数(注意是剩余最大步数,不包括A[i])。

jump[i] = max{jump[i-1], A[i-1]} - 1.

遇到jump[i]<0就返回false.

另外这里只用到jump[i-1],因此不需要一个额外数组来存储jump,只要一个变量就行了。

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


0 0
原创粉丝点击