45. &55 Jump Game II

题目要求:

一个数组存储了非负整形数据,数组中的第 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]))
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容