原题
https://leetcode.cn/problems/jump-game/description/
思路
贪心, 每次跳到下一步能到的最远位置
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def canJump(self, nums: List[int]) -> bool:
if len(nums) == 1:
return True
# 当前能到的最大索引
curr = 0
# 下一步能到的的最大索引
next = 0
for i in range(len(nums) - 1):
next = max(next, i + nums[i])
if i == curr:
# 需要跳跃
curr = next
if curr >= len(nums) - 1:
return True
return False
Go代码
func canJump(nums []int) bool {
if len(nums) == 1 {
return true
}
// 当前能到的最大索引
curr := 0
// 下一步能到的的最大索引
next := 0
for i := 0; i < len(nums)-1; i++ {
next = max(next, i+nums[i])
if i == curr {
// 需要跳跃
curr = next
if curr >= len(nums)-1 {
return true
}
}
}
return false
}

被折叠的 条评论
为什么被折叠?



