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

  • 相关阅读:
    O'Reilly总裁提姆奥莱理:什么是Web 2.0
    在MFC程序中显示JPG/GIF图像
    VC窗体设计集锦
    VxWorks使用说明书
    关于双缓冲绘图之二
    如何将EVC4工程升级到VS.NET2005工程
    某个正在运行的程序的CPU占用率
    如何去掉回车键和取消键
    探索NTFS
    ARM上的C编程
  • 原文地址:https://www.cnblogs.com/zhongju/p/14106985.html
Copyright © 2011-2022 走看看