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
- 57 leetcode - Jump Game II
- LeetCode: Jump Game II
- LeetCode Jump Game II
- LeetCode: Jump Game II
- [Leetcode] Jump Game II
- [LeetCode] Jump Game II
- [Leetcode] Jump Game ii
- leetcode Jump Game II
- leetcode Jump Game II
- [LeetCode]Jump Game II
- [leetcode]Jump Game II
- LeetCode-Jump Game II
- [leetcode] Jump Game II
- LeetCode - Jump Game II
- LeetCode:Jump Game II
- LeetCode | Jump Game II
- 【Leetcode】Jump Game II
- LeetCode Jump Game II
- cocos2dx 中tinyxm12 解析Xml文件,换行问题
- day16Map
- Material Design学习之CollapsingToolbarLayout
- Ajax异步封装
- java集合
- 57 leetcode - Jump Game II
- axis1实现webservice
- Leetcode Perfect Squares 279
- POJ 3415 Common Substrings 笔记
- WX-组件-基础内容
- OpenGL 入门6
- LCA之倍增及ST算法
- java swing Jtable 排序支持中文
- 安装mysql时的修改初始密码 mac