天天看点

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 < :
            return 

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

        return min_step[-]

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

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

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

if __name__ == "__main__":
    s = Solution()
    print s.jump([,,])
    print s.jump([,,,,])
    print s.jump([,,,,])
    print s.jump([,,,,])