[LeetCode]Jump Game II(贪心&&DP!!!!!)
2015-07-18 13:27
363 查看
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.)
题目的意思是求出到达终点的最小步数,看似可以用Dp来做,就会发现dp实际上会TLE。使用贪心来处理
原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。
这种处理方法可以看成是对step的dp处理
类似的题目有Container With Most Water
还有另外一种比较好理解的思路是我们每次都维护一个区间,这个区间表示的是第i步能到达的最大范围,
递推的方法为:每次都遍历一遍当前区间内的所有元素,从一个元素出发的最远可达距离是index+array[index],那么下一个区间的左端点就是当前区间的右端点+1,下一个区间的右端点就是当前区间的max(index+array[index]),以此类推,直到区间包含了终点,统计当前步数即可。
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.)
题目的意思是求出到达终点的最小步数,看似可以用Dp来做,就会发现dp实际上会TLE。使用贪心来处理
原来的全局最优现在要分成step步最优和step-1步最优(假设当前步数是step)。当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)。
这种处理方法可以看成是对step的dp处理
public int jump(int[] A) { if(A==null || A.length==0) return 0; int lastReach = 0; int reach = 0; int step = 0; for(int i=0;i<=reach&&i<A.length;i++) { if(i>lastReach) { step++; lastReach = reach; } reach = Math.max(reach,A[i]+i); } if(reach<A.length-1) return 0; return step; }
类似的题目有Container With Most Water
还有另外一种比较好理解的思路是我们每次都维护一个区间,这个区间表示的是第i步能到达的最大范围,
递推的方法为:每次都遍历一遍当前区间内的所有元素,从一个元素出发的最远可达距离是index+array[index],那么下一个区间的左端点就是当前区间的右端点+1,下一个区间的右端点就是当前区间的max(index+array[index]),以此类推,直到区间包含了终点,统计当前步数即可。
public class Solution { public int jump(int[] A) { if (A.length == 1) return 0; int max = 0, count = 1, begin = 0, end = A[0]; while (end < A.length - 1) { count++; int index = begin; for (; index <= end; index++) { max = Math.max(max, index + A[index]); } begin = index; end = max; } return count; } }
相关文章推荐
- LINUX分区
- 移动web适配
- 小题一道~
- socket套接字TCP API
- iOS 7从 NSURLConnection 到 NSURLSession
- Codeforces 429 A. Xor-tree
- hdu 1712, multiple-choice knapsack,
- Sass学习之路:Sass、Compass安装与命令行
- 【android安全】保护app本地数据文件
- KMP next数组的求法
- ios开发动物园管理 继承多态的实现
- 4Sum
- javascript 字符串加减法
- FireEvent结合WSH实现右键菜单操作
- 运行Maven时出现-Dmaven.multiModuleProjectDirectory system propery is not set.错误
- 网页中<li>分列显示
- 链接器简介
- 教你透彻了解红黑树
- 解决Virtual Box 安装Mac OS X当出现“hfs: summary table not allowed on FS with block size of 2048”问题
- 你必须知道的指针基础-1.预备篇:搭建GCC开发环境