算法55. Jump Game

55. Jump Game
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.

给一个非负整数的数组,从头开始。每一个元素的值表示你最多能跳多少步。
计算下,是否能从头跳到尾。

class Solution {
    public boolean canJump(int[] nums) {
        
    }
}

解:
采用数学归纳法:要能从第 n-1 步跳到第 n 步,要么 n-1 大于等于1,如果不等,那就得 n-i 大于等于 i。然后去看是否能跳到第i步,以此类推,看最后是否能跳到 0。

以下为代码:

public boolean canJump(int[] nums) {
    int lastPos = nums.length - 1;
    for (int i = nums.length - 1; i >= 0; i--) {
        if (i + nums[i] >= lastPos) {
            lastPos = i;
        }
    }
    return lastPos == 0;
}

你可能感兴趣的:(算法55. Jump Game)