Jump Game 解答
2015-10-03 07:59
387 查看
Question
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.
Solution
We apply Greedy Algorithm here to solve the problem. Key to the solution is to check largest distance that every element can reach.1) when the current position can not reach next position (return false)
2) when the maximum index can reach the end (return true).
public class Solution { public boolean canJump(int[] nums) { if (nums == null || nums.length <= 1) return true; int max = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == 0 && max <= i) return false; if (i + nums[i] > max) max = i + nums[i]; if (max >= nums.length - 1) return true; } return false; } }
相关文章推荐
- 【iOS 开发】Objective - C 面向对象 - 方法 | 成员变量 | 隐藏封装 | KVC | KVO | 初始化 | 多态
- 【iOS 开发】Objective - C 面向对象 - 方法 | 成员变量 | 隐藏封装 | KVC | KVO | 初始化 | 多态
- 1.2.3 加载第三部分代码—system模块(2)
- 88. Merge Sorted Array (Array)
- 少女时代擦玻璃屏保
- hadoop2.7环境的编译安装
- CodeForces 3A Shortest path of the king(贪心)——Codeforces Beta Round #3
- 1.2.3 加载第三部分代码—system模块(1)
- 1.2.2 加载第二部分代码—setup(2)
- 实时系统的基本特性?
- Reverse Integer
- 学习方法总结
- 1.2.2 加载第二部分代码—setup(1)
- Pascal's Triangle II
- ViewPager不显示加载的图片或者报错
- iOS—修改AFNetworking源文件可接收text/html的方法
- 1.2.1 加载第一部分代码—引导程序(bootsect)
- PS 利用置换滤镜制作动感水波字
- 1.1.2 BIOS在内存中加载中断向量表和中断服务程序
- PS 水波效果