- 55. Jump Game
思路:[greedy] 得到所能走到的最大距离,与最终结果比较
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
max_nums=nums[0]
x=0
while x<min(max_nums+1,len(nums)):
if nums[x]+x>max_nums:max_nums=nums[x]+x
x+=1
return max_nums>=len(nums)-1
下面的思路更清晰
class Solution:
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
#greedy reach最远可达的位置
reach = 0
for i in range(len(nums)):
#reach = max(reach, i+nums[i])
if i > reach or reach >= len(nums)-1:
break
reach = max(reach, i+nums[i])
return reach >= len(nums)-1
- 45. Jump Game II
思路:算出第一步最远距离,第二步最远距离,直到符合要求,
# 45. Jump Game II
#
class Solution:
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==1:return 0
# 步数
steps=1
# 每一步所能到达的最远
max_reach=nums[0]
# 每一个位置所能到达最远
step_reach=nums[0]
x=0
while x<len(nums):
# 切换步数条件
if max_reach<x:
steps+=1
max_reach=step_reach
step_reach=max(step_reach,x+nums[x])
x+=1
if max_reach>len(nums)-2:return steps