[LeetCode]题解(python):045-Jump game II



题目来源


https://leetcode.com/problems/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.


题意分析


Input: a list named nums

Output:minimum steps to the last index

Conditions:最小的步数到达最后


题目思路


网上大牛的代码好厉害= =想了老半天才想懂,主要思想是每一次跳跃时记录一个能到达的最大位置,然后在这个位置前记录所能到达的位置的最大位置(不断更新),当到达之前步数记录最大位置时,step+1,然后赋值新的最大位置,然后继续遍历下去(感觉这样说我都不明白……直接看代码)


AC代码(Python)


 1 class Solution(object):
 2     def jump(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         last = 0
 8 
 9         #the number steps
10         step = 0
11 
12         #current  max
13         curr = 0
14 
15         for i in range(len(nums)):
16             if i > last:
17                 step += 1
18                 last = curr
19             curr = max(curr, i + nums[i])
20 
21         return step
原文地址:https://www.cnblogs.com/loadofleaf/p/5084160.html