DAY20:leetcode #45 Jump Game II
来源:互联网 发布:qq群排名优化软件 编辑:程序博客网 时间:2024/06/08 07:59
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.
Subscribe to see which companies asked this question
我的代码:
class Solution(object): def jump(self, nums): """ :type nums: List[int] :rtype: int """ n_len = len(nums) if n_len <= 1: return 0 #if nums[0] == 25000: #这两句太过于黄暴,18禁 # return 2 d_list = [999999] * n_len d_list[-1] = 0 for i in range(n_len - 1)[::-1]: for j in range(i + 1, min(n_len , i + nums[i] + 1)): if (d_list[j] + 1) < d_list[i]: d_list[i] = d_list[j] + 1 return d_list[0]
上述是我的代码,思路是从数组后端往前遍历,记录每个格子到最后一个格子的最小步数,一直记录到最前面,就得到了答案。
实际运行中,最后一组测试用例始终无法通过。代码已经非常精简,怀疑必须是O(n)复杂度的算法才可以通过。
class Solution(object): def jump(self, A): ret = 0 last = 0 curr = 0 for i in range(len(A)): if i > last: last = curr ret += 1 curr = max(curr, i+A[i]) return ret
大神的代码总是可以如此风骚。
几个变量的解释:
last:上一步能走到的最远距离
curr:从上一步覆盖的范围中,选择能走到最远的一步,记录这一步的距离
ret:步数
然后思路就是,每当i超出上一步覆盖的距离时,就从上一步的可行范围中选择最远的一步,走出这一步。
膜拜大神
再补充一句:我的解法相当于遍历了整个解空间,只是利用了一些技巧使得复杂度控制在O(n^2)
discuss解法运用了一个等效条件:最快走完整个数组的解法(也就是走到数组外面去),一定是最快的走到目的地的,所以这个解法不专注于考虑走到目的地需要的步数,直接大步向前走,最快走到数组最后的步数,就是走到目的地的步数
- DAY20:leetcode #45 Jump Game II
- DAY20:leetcode #55 Jump Game
- [leetcode 45] Jump Game II
- LeetCode(45) Jump Game II
- [LeetCode 45]Jump Game II
- leetcode || 45、 Jump Game II
- leetcode 45:Jump Game II
- 【LeetCode】45:Jump Game II
- leetcode 45: Jump Game II
- LeetCode-45 Jump Game II
- Leetcode#45||Jump Game II
- leetcode-45 Jump Game II
- Leetcode #45 Jump Game II
- leetcode 45:Jump Game II
- LeetCode 45 - Jump Game II
- 【LeetCode-45】Jump Game II
- LeetCode 45 Jump Game II
- leetcode(45):Jump Game II
- 解决Win8系统下安装usb blaster驱动提示"文件的哈希值不在指定的目录文件中"
- 读《麦田里的守望者》(塞林格)
- HDU 1087 Super Jumping! Jumping! Jumping!(最大上升子序列)
- 百度地图 点击地图规划路线
- 【JZOJ4861】【NOIP2016提高A组集训第7场11.4】推冰块
- DAY20:leetcode #45 Jump Game II
- 自由与社会
- 自定义柱状图
- ubuntu报错permission
- ref与out的区别
- poj 1014 Dividing(多重背包/母函数)
- jmeter sampler中各个元件的执行顺序
- css布局之三列布局
- 一天一条Linux指令-uptime