[LeetCode55]Jump Game
来源:互联网 发布:触摸屏查询网站源码 编辑:程序博客网 时间:2024/05/29 19:28
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
.
Analysis:
Note that the A[i] means the maximum jump length. In other words, it is possible that we move j step (<A[i]) when we at A[i], e.g. if A[i]=2, we can move either 1 or 2 steps.
The simple but time-consuming way is O(n^2). Set every future step true according to the A[i]. But this only can pass the small test.
A better idea is use another variable to save the number of steps available. Just a little bit different from the O(n^2) one , see code for more details.
Use one variable to store current maximum jump index
Java
public boolean canJump(int[] A) { int jmax = 0; for(int i = 0;i<A.length;i++){ if(i<=jmax){ jmax = Math.max(jmax, A[i]+i); }else {return false;} } return true; }
c++
bool canJump(int A[], int n) { int maxCover = 0; for(int start = 0; start<=maxCover &&start<n;start++){ if(A[start]+start > maxCover) maxCover = A[start]+start; if(maxCover >=n-1) return true; } return false; }
- [LeetCode55]Jump Game
- Leetcode55 Jump Game
- leetcode55 Jump Game
- LeetCode55. Jump Game
- LeetCode55. Jump Game
- LeetCode55 Jump Game
- leetcode55. Jump Game
- leetcode55. Jump Game
- leetcode55-jump game
- leetcode55. Jump Game (贪心)
- LeetCode55. Jump Game
- LeetCode55——Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- Jump Game
- 2014 BUAA 选拔赛第一场
- 【LeetCode】4Sum
- 《算法导论》二分法排序
- JavaScript Closure
- jquery中后代元素和子元素的区别
- [LeetCode55]Jump Game
- Mysql中如何将时间戳转化为常用日期格式
- [C/C++]常见错误积累
- 【LeetCode】Remove Nth Node From End of List
- [LeetCode45]Jump Game II
- html压缩工具html-minifier -- nodejs常用模块(4)
- VS DLL修改lib生成路径
- Swift编程入门
- VS编写Dll