Loading

[LeetCode] 55. Jump Game(跳跃游戏)

Description

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.
判断你能否以此到达数组的最后一个下标。

Examples

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 * 10^4
  • 0 <= nums[i][j] <= 10^5

Solution

这题如果采用从前往后的遍历,那么无论怎么做,似乎都会在一组很大的数据上 TLE 或者 MLE。Discussion 里的做法十分巧妙:反向行进,从最后一个下标开始往前找最小的能够跳到此处的下标,如果最后能跳到第一个下标就表示找到了。代码如下:

class Solution {
    fun canJump(nums: IntArray): Boolean {
        var last = nums.lastIndex

        for (i in nums.lastIndex - 1 downTo 0) {
            if (i + nums[i] >= last) {
                last = i
            }
        }

        return last <= 0
    }
}

I solve most of the questions, but when I look into the solutions, I always end up thinking, "WHY DID I NOT THINK OF THIS BEFORE?"

posted @ 2020-12-09 09:50  Zhongju.copy()  阅读(99)  评论(0编辑  收藏  举报