Skip to content

Latest commit

 

History

History
62 lines (41 loc) · 1.44 KB

20210102.md

File metadata and controls

62 lines (41 loc) · 1.44 KB

Algorithm

55. Jump Game

Description

Given an array of non-negative integers nums, 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: nums = [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: nums = [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.

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 0 <= nums[i] <= 105

Solution

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

Discuss

倘若每次都是向前跳跃,哪怕每次跳一格也可以到达终点啊,所以说数组中肯定有位置值为0,无论怎么跳都会经过这一格。这样我们首先找到数组中为0的索引last, 然后从这个位置开始向前遍历,判断是否存在一个索引为i的,且nums[i]>last-i,从而使得可以跳过这个为0 的位置,如果找不到这个last,说明跳不到最后一格。

Review

Tip

Share