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

[LeetCode] 45. Jump Game Ⅱ(跳躍遊戲之二)

Description

Given an array of non-negative integersnums, you are initially positioned at the first index of the array.
給定一非負整數陣列 num,你最初位於陣列的 0 下標處。

Each element in the array represents your maximum jump length at that position.
數組裡的每一個元素表示你在此處能跳躍的最遠距離。

Your goal is to reach the last index in the minimum number of jumps.
你的目標是最少步數內抵達陣列的最後一個下標。

You can assume that you can always reach the last index.
你可以假定輸入總是合法的(一定能到達最後一個下標)。

Examples

Example 1

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2

Input: nums = [2,3,0,1,4]
Output: 2

Constraints

  • 1 <= nums.length <= 3e4
  • 0 <= nums[i] <= 1e5

Solution

由於題目明確說明解一定存在,故只需考慮最遠能走多遠。初始化兩個變數 currentFarthest 表示目前能到達的最遠下標,currentEnd 表示當前跳躍的『終點』。遍歷每個下標 i 並更新 currentFarthest,若抵達 currentEnd,則步數加一,更新『終點』為 currentFarthest,程式碼如下:

import kotlin.math.max

class Solution {
    fun jump(nums: IntArray): Int {
        var result = 0
        var currentEnd = 0
        var currentFarthest = 0

        for (i in 0 until nums.lastIndex) {
            currentFarthest = max(currentFarthest, i + nums[i])
            if (i == currentEnd) {
                result++
                currentEnd = currentFarthest
            }
        }
        return result
    }
}