Jump Game
来源:互联网 发布:大连海关数据分中心 编辑:程序博客网 时间:2024/05/01 05:29
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.
Determine if you are able to reach the last index.
For example:
A = [2,3,1,1,4], return true.
A = [3,2,1,0,4], return false.
思路:刚刚开始的时候,看到网上说用贪心法,每一次选择最最远的步数,思路很混乱,不知道怎么选择,万一每一次选择最远的距离,并不能跳到最后该怎么回溯呢。
用动态规划,用一个变量step来记录在当前位置时所能够走到的最远的位置,遍历一遍数组,step就是从i=0出发能够走到的最远的位置,如果此时step小于n-1说明不管怎么走,都不可能走到数组的最后。否则是可以走到数组的最后的。
public class Solution { public boolean canJump(int[] nums) { int n=nums.length; if(n==0) return false; int step=nums[0]; for(int i=1;i<=step&&i<n;i++) { step=step>(i+nums[i]) ? step : i+nums[i]; } if(step<n-1) return false; return true; }}
0 0
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Spring 3整合Quartz 2实现定时任务一:常规整合
- android自定义Seekbar你还将你的拖动数值显示在旁边固定的TextView上么?
- 在CentOS下搭建自己的Git服务器
- 从源码角度分析linearLayout测量过程以及weight机制
- iOS_NSTimer的那些事(二)
- Jump Game
- IE8兼容placeholder
- 64位ubuntu:arm-linux-gcc –v 提示找不到该文件或目录
- XIB中Cell出现警告消除方法
- Git避免每次远程交互都需要输入密码的设置
- LeetCode
- OOP版电子词典
- Java多态性详解——父类引用子类对象
- 多重背包问题