天天看點

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([,,,,])