https://leetcode.com/problems/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.
For example:A = [2,3,1,1,4]
, return true
.
A = [3,2,1,0,4]
, return false
.
Subscribe to see which companies asked this question.
说明
- idx为所能触及到的最远位置
- for i in range(len(A))
- 当前点所能到达的最远距离为i+A[i]
- 若最远距离大于len(A),则可以抵达
- 需要考虑有时候i并不需要按顺序遍历len(A) 因为i可以跳跃到i+A[i]处
- 所以每次循环的新的idx = max(idx, i+A[i])
- 若最终的 idx>= len(A)-1,则可以抵达终点i
比较特殊的特殊情况
- A=[0]
- A=[2, 0, 0]
# time O(n)
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
idx = 0
for i in range(len(nums)):
if idx < i:
break
idx = max(idx, i+nums[i])
return idx >= len(nums) - 1