#55 Jump Game——Top 100 Liked Questions

待我称王封你为后i 2022-01-30 13:01 240阅读 0赞

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.

Example 1:

  1. Input: [2,3,1,1,4]
  2. Output: true
  3. Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.

Example 2:

  1. Input: [3,2,1,0,4]
  2. Output: false
  3. Explanation: You will always arrive at index 3 no matter what. Its maximum
  4. jump length is 0, which makes it impossible to reach the last index.

“””
第一次:num[i]+i为i位置所等到达的最大距离,遍历后如果最大距离小于L-1,说明不能到达末尾,如果>=L-1,说明肯定能到达末尾。同时在每次遍历时,应使dist>=i,这是为了避免元素为零的特例
“””

  1. class Solution(object):
  2. def canJump(self, nums):
  3. """
  4. :type nums: List[int]
  5. :rtype: bool
  6. """
  7. L = len(nums)
  8. dist = 0
  9. for i in range(L-1):
  10. if dist >= i:
  11. dist = max(dist, i + nums[i])
  12. if dist < L - 1:
  13. return False
  14. return True

“””

Runtime: 72 ms, faster than 58.03% of Python online submissions for Jump Game.

Memory Usage: 13.3 MB, less than 33.52% of Python online submissions for Jump Game.

“””

发表评论

表情:
评论列表 (有 0 条评论,240人围观)

还没有评论,来说两句吧...

相关阅读