55. Jump Game - jiejackyzhang/leetcode-note GitHub Wiki

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.

解题思路为:

  1. 从后往前考虑,from length-1 to 0;
  2. 记下最左边的可以走到最后的index,为lastPos;
  3. 对于下标i的元素,如果i+nums[i] >= lastPos,则update lastPos = i;
  4. 如果最后lastPos == 0,则表明从0可以走到最后。
public class Solution {
    public boolean canJump(int[] nums) {
        int lastPos = nums.length - 1;
        for(int i = nums.length - 2; i >= 0; i--) {
            if(i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
}