码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-28 23:20:55      阅读:317      评论:0      收藏:0      [点我收藏+]

标签:



题目来源


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

 

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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5084160.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!