LeetCode刷题笔录 Jump Game II
来源:互联网 发布:淘宝crm软件排名 编辑:程序博客网 时间:2024/06/05 07:13
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.)
拿到这题,第一反应就是dynamic programming了。以x[i]表示第i个element需要的最少步数,有这样的递归方程:
x[i] = min(x[k]) + 1 where 0<=k<i and A[k] >= i-k.
迅速写出代码:
public class Solution { public int jump(int[] A) { int x[] = new int[A.length]; x[0] = 0; for(int i = 1; i < x.length; i++){ //find the min x[k] int min = Integer.MAX_VALUE; for(int k = 0; k < i; k++){ if(A[k] < i - k) continue; else{ if(x[k] < min) min = x[k]; } } x[i] = min + 1; } return x[x.length - 1]; }}问题是,在一个有25000个元素的test case里因为超时挂掉了。。。这个算法用O(n^2)时间,想了半天也不知道如果用dp的话还能怎么改进了。
其实这题里面每个数字表示的是能跳得最大距离,而不是只能跳这么远。而且最后也没有要求怎么跳,用dp有点大材小用了。看到大神的解法,用贪心就行其实。
public class Solution { public int jump(int[] A) { int ret = 0; int last = 0; int curr = 0; for (int i = 0; i < A.length; ++i) { if (i > last) { last = curr; ++ret; } curr = Math.max(curr, i+A[i]); } return ret; }}
觉得自己真是弱爆了...
另外找到这篇blog用中文解释了一下这个解法。
果然自己好弱。
0 0
- LeetCode刷题笔录 Jump Game II
- LeetCode刷题笔录Jump Game
- [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
- Android如何运行真机在eclipse上调试应用
- android图片加水印,文字
- E1载波
- 交互设计笔记(4)——理解用户:定性研究
- 曼彻斯特编码
- LeetCode刷题笔录 Jump Game II
- 海明码
- CRC校验
- 串口控件MSCOMM的注册方法(使用MSCOMM串口控件程序的发布问题)
- 滚动条ScrollView、HorizontalScrollView
- 图文按钮、图文TextView
- android中network的连接不能在直接在主线程运行
- MSComm的串口通信程序,在没有安装Vc的机器上没有办法运行 MSComm控件注册
- 朴素贝叶斯文本分类算法源代码