LeetCode.55 Jump Game
来源:互联网 发布:java try的用法 编辑:程序博客网 时间:2024/06/05 05:40
题目:
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
.
class Solution { public boolean canJump(int[] nums) { //给定非负数的数组,每个元素表示你可以走的最大步数(意味着你可以选择更小的或者),判断是否可以走到最末尾 //思路:先求出当前节点之前能到的最大值,与当前节点下标比较,若小于,说明根本无法到达该节点 //直接返回false。若到达该节点,且该节点能到达的最大范围超过或者等于num的长度,则直接返回true。 if(nums.length==0||nums==null) return true; //创建preSum数组表示当前节点能到达的最大范围 int [] preSum=new int[nums.length]; int max=0; for(int i=0;i<nums.length;i++){ if(max<i){ //说明无法到达该节点 return false; } preSum[i]=i+nums[i]; if(preSum[i]+1>=nums.length){ //可以直接到达最后 return true; } max=Math.max(max,preSum[i]); } return true; }}
分析(参考答案):
class Solution { public boolean canJump(int[] nums) { int index = nums.length - 1; for (int i = nums.length - 2; i >= 0; i--) { if (nums[i] + i >= index) index = i; } return index == 0; }}
阅读全文
0 0
- LeetCode 55: Jump Game
- [leetcode 55] Jump Game
- LeetCode(55) Jump Game
- [LeetCode 55]Jump Game
- leetcode || 55、Jump Game
- LeetCode-55-Jump Game
- leetcode-55 Jump Game
- Jump Game - LeetCode 55
- 【Leetcode】Jump Game #55
- Leetcode #55 Jump Game
- 【LeetCode】55:Jump Game
- LeetCode(55) Jump Game
- Leetcode#55||Jump Game
- (leetcode #55)Jump Game
- Leetcode 55 - Jump Game
- 【leetcode】【55】Jump Game
- LeetCode 55 - Jump Game
- 【LeetCode-55】Jump Game
- MySql安装与使用图文教程【推荐】
- sql常用语句
- MyBatis之自查询使用递归实现 N级联动效果(两种实现方式)
- Python学习_我该怎么使用字典
- 浅谈Spring注解
- LeetCode.55 Jump Game
- 机器学习入门--MNIST(一)
- IBM服务器引导盘serverguide 下载
- Somethings about the coding in Python
- UBoot:ENTRY等宏的展开,CPSR寄存器的设置(stat.S)
- sql排序问题
- Android音频子系统,音频流的回放(四)
- 【Java】【线程同步】sleep,join,yield,synchronized,wait,notify
- HDU 1029