zoukankan      html  css  js  c++  java
  • [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?"

  • 相关阅读:
    ORA-00119: invalid specification for system parameter LOCAL_LISTENER
    local_listener参数的作用!
    DDL为什么不能rollback?
    LGWR和DBWn的触发条件
    修改spfile位置
    初识oracle重做日志文件
    ORACLE AUDIT 审计
    Oracle SQL_TRACE使用小结
    Web API(六):使用Autofac实现依赖注入
    JavaScript:属性的操作
  • 原文地址:https://www.cnblogs.com/zhongju/p/14106985.html
Copyright © 2011-2022 走看看