57 leetcode - Jump Game II

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
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.
For example:
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.)
Note
You can assume that you can always reach the last index.
假设每一个都能到达最后一个索引
'''
class Solution(object):
    def jump(self, nums):
        """
        超时了...醉了...
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        if length < 2:
            return 0

        min_step = [length] * length
        min_step[0],min_step[1] = 0,1
        for index,val in enumerate(nums):
            for jump in range(index + 1,index + val + 1):
                tmp = min_step[index] + 1
                if jump < length and min_step[jump] > tmp:
                    min_step[jump] = tmp

        return min_step[-1]

    def jump(self, nums):
        """
        type nums: List[int]
        rtype: int
        """
        length = len(nums)
        if length < 2:
            return 0

        if (nums[0] + 1) >= length:
            return 1

        max_dis1 = max_dis2 = nums[0]
        target = length - 1
        min_step = 1
        index = 1
        while index < length:    #寻找每一步能走的最大值
            if index <= max_dis1:#在走一步的范围内,查看下一步最远走到哪里
                max_dis2 = max(max_dis2,index + nums[index])
                if (max_dis2 + 1) >= length:
                    return min_step + 1
                index += 1
            else:                #超过了这步的最远距离,步数加一,更新成下一步能走的最远距离
                min_step += 1
                max_dis1 = max_dis2

if __name__ == "__main__":
    s = Solution()
    print s.jump([10,4,2])
    print s.jump([2,3,0,1,4])
    print s.jump([1,1,1,1,1])
    print s.jump([1,1,2,1,1])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值