57 leetcode - Jump Game II

来源:互联网 发布:mac git 添加忽略文件 编辑:程序博客网 时间:2024/04/29 19:12
#!/usr/bin/python# -*- coding: utf-8 -*-'''Jump Game IIGiven 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.)NoteYou 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_dis2if __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])
0 0
原创粉丝点击