1. 程式人生 > 實用技巧 >[LeetCode] 55. Jump Game(跳躍遊戲)

[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?"