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

  • 相关阅读:
    C#调用WinAPI(转)
    C++升级到C#,内存数据读取问题
    锦里未成行
    创业用人九招成功法则
    彩霞满天
    特别提醒: 7种不良习惯直接影响你晋升!
    生意大展示:49种简易创业方法大比拼
    阴阳天
    受益无穷的28条职场语录
    哈佛:创业者需具备的素质及培养方法
  • 原文地址:https://www.cnblogs.com/zhongju/p/14106985.html
Copyright © 2020-2023  润新知