给定一个数组,判断从开始能否走到结束,最多需要几步?
2016-03-24 18:52
459 查看
1、给定一个非负数组,数组中的元素代表从当前位置可以向后跳几步,判断能否走到数组末尾。例如:A = [2,3,1,1,4], return true;A = [3,2,1,0,4], return false.
2、求出从数组开始到末尾最少可以跳几次。例如:A = [2,3,1,1,4],则最少需要2步,2–>3–>4。
2.1、最直观,递归
2.2、动态规划,保存之前求过的值
2.3、维持两个指针,一个表示当前最远可以跳到哪一步,一个表示下一步最远可以跳到哪一步。遍历原数组同时更新指针。
public boolean canJump(int[] nums) { int maxIndex = nums.length-1; int maxJump = nums[0]; for(int i = 0; i <= maxJump; i++){ maxJump=Math.max(maxJump,i+nums[i]); if(maxJump>=maxIndex) return true; } return false; }
2、求出从数组开始到末尾最少可以跳几次。例如:A = [2,3,1,1,4],则最少需要2步,2–>3–>4。
2.1、最直观,递归
public int jump(int[] nums) { if(nums.length==1)return 0; return getLen(nums,0); } public int getLen(int []nums,int i){ if(i>=nums.length-1)return 0; int val=nums[i]; int min=nums.length; for(int j=i+1;j<=i+val;j++){ min=Math.min(getLen(nums,j),min); } return min+1; }
2.2、动态规划,保存之前求过的值
public int jump(int[] nums) { if(nums.length==1)return 0; int dp[]=new int[nums.length]; int temp=0,len=nums.length; for(int i=len-2;i>=0;i--){ temp=nums[i]; dp[i]=len; temp+=i; for(int j=i+1;j<=temp&&j<len;j++){ dp[i]=Math.min(dp[i],dp[j]); } dp[i]++; } return dp[0];
2.3、维持两个指针,一个表示当前最远可以跳到哪一步,一个表示下一步最远可以跳到哪一步。遍历原数组同时更新指针。
public int jump(int[] nums) { if (nums.length <= 1)return 0; int i = 0, n = nums.length, lc = 0, ln = 0, step = 1; // lc means the longest distance can achieve by current jump // ln means the longest distance can achieve by next jump lc = nums[0]; ln = nums[0]; // Initialize to index 0, the start point. for (i = 1; i < n; ++i) { if (i > lc){ // current jump cannot get index i -->>> must jump one more time. lc = ln; step++; } if (i + nums[i] > ln)ln = i + nums[i]; // maintain the furthest distance of next jump can get if (lc >= n - 1) return step;// current jump can achieve the last index } return step; }
相关文章推荐
- 迷宫最少步数的求解(利用队列)
- NYOJ--58(搜索)-题目-----------------------------最少步数
- nyoj 最少步数
- nefu 628 Garden visiting(非降路径模板题)
- nyoj58 最少步数
- swift学习入门笔记1
- mybatis打印日志的log4j.xml配置
- 学习asp.net
- 派生类的析构函数
- springmvc 例
- spring学习笔记(7)AOP前夕[2]CGLib动态代理实例解析
- 第七章 虚拟机类加载机制
- HTTP请求
- poj3311(状态压缩dp)
- ZJOI2016一试 酱油记
- 破解电脑开机密码
- 编译hi3536平台NVR软件debug版本时出现clock_gettime、clock_getres未定义的引用
- C++文件操作
- java回顾篇——java环境的搭建
- Could not obtain transaction-synchronized Session for current thread