jump game 55/45
题目描述
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.
每个位置上的数字代表了最多可以向右跳多少步,问能不能跳到最右边的位置。
解题思路
贪心策略是我们每次都选取最优的策略局部最优
使用一个变量reach保存当前能到达的最后位置索引,那么在每个位置的时候判断这个位置能不能到达,即位置的索引大于了reach说明前面无论怎么走也走不到这个位置,就返回False好了。如果这个位置可以到达,那么要维护一下这个reach,更新策略是当前位置索引+这个数字代表的能向右走多少步,这个代表了到达当前位置的时候向右能到达的最远距离,在这个最远距离以内的任何位置都能到,因为每次跳的步数可以变小的。那么进行了这么一次循环以后,每个位置都判断为能到达,所以结果返回True就好了。
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
reach = 0
for i, num in enumerate(nums):
if i > reach:
return False
reach = max(reach, i + num)
return True
浙公网安备 33010602011771号