美文网首页
45. &55 Jump Game II

45. &55 Jump Game II

作者: Jonddy | 来源:发表于2018-03-08 18:18 被阅读0次
题目要求:

一个数组存储了非负整形数据,数组中的第 i 个元素num[i],代表了可以从数组第i个位置最多向前跳跃nums[i]步;确认可以从第0个位置跳跃到数组最后的位置,求最少的跳跃次数。

Examples:

Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Notion:
You can assume that you can always reach the last index.

解题思路:
  • 既然一定可以跳到最后一个元素那里,那么,明确什么时候跳最合适就成了关键!!!
  • 每次超过记录的reachable就增加一次跳跃次数
代码:
# pass on leetcode because of time limit
class Solution(object):
    def jump(self, A):
        """
        :param A: List[int]
        :return: int
        """
        jump_count = 0
        reachable = 0
        curr_reachable = 0
        for i, length in enumerate(A):
            if i > reachable:
                return -1
            if i > curr_reachable:
                curr_reachable = reachable
                jump_count += 1
            reachable = max(reachable, i+length)
        return jump_count

if __name__ == "__mian__":
    print(Solution.jump(self=None, A=[2, 3, 1, 1, 4]))

相关文章

  • [DP]45. Jump Game II

    前篇 55. Jump Game 45. Jump Game II 感谢Jason_Yuan大神优秀的解析:链接 ...

  • Leetcode-45Jump Game II

    45. Jump Game II Given an array of non-negative integers,...

  • dp

    10 Regular Expression Matching 45. Jump Game II 62 Unique...

  • [Greedy]45. Jump Game II

    分类:Greedy 时间复杂度: O(n) 45. Jump Game II Given an array of ...

  • 坐标型--(b)跳格子

    1) jump game I, II (LeetCode 55, 45) [ 要求] 给出jump power数组...

  • 45. &55 Jump Game II

    题目要求: 一个数组存储了非负整形数据,数组中的第 i 个元素num[i],代表了可以从数组第i个位置最多向前跳跃...

  • 45. Jump Game II

    题目 Given an array of non-negative integers, you are initi...

  • 45. Jump Game II

    https://leetcode.com/problems/jump-game-ii/#/description

  • 45. Jump Game II

    问题 Given an array of non-negative integers, you are initi...

  • 45. Jump Game II

    原文地址http://www.lintcode.com/problem/jump-game-ii/Given an...

网友评论

      本文标题:45. &55 Jump Game II

      本文链接:https://www.haomeiwen.com/subject/mszlfftx.html