Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

55. 跳跃游戏 #24

Open
Geekhyt opened this issue Feb 5, 2021 · 0 comments
Open

55. 跳跃游戏 #24

Geekhyt opened this issue Feb 5, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Feb 5, 2021

原题链接

先明确,题目给出的非负整数数组中的每个位置的数字都对应着其最大的跳跃能力,要求我们判断能否到达最后一个下标。

到达或是超过都是可以满足要求的,因为每个位置的数字代表的是其最大的跳跃能力,而不是固定的跳跃能力(大富翁游戏)。

所以只需要判断能否到达终点即可:

  1. 定义能够跳的最远位置 canJumpMax,初始化为 0。
  2. 遍历数组,如果当前值大于 canJumpMax 则不能跳到末尾返回 false。
  3. 每个位置都可以作为起跳点,将 canJumpMax 不断更新,i + nums[i] 也就是当前位置能够跳到的最远位置。
  4. 如果可以跳到最后即成功返回 true。
const camJump = function(nums) {
    let canJumpMax = 0
    let len = nums.length
    for (let i = 0; i < len; i++) {
        if (i > canJumpMax) {
            return false
        }
        canJumpMax = Math.max(canJumpMax, i + nums[i])
    }
    return true
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(1)
@Geekhyt Geekhyt added the 中等 label Jun 4, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant