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.
Notice
This problem have two method which is Greedy
and Dynamic Programming
.
The time complexity of Greedy
method is O(n)
.
The time complexity of Dynamic
Programming method is O(n^2)
.
贪心思路: 用farthest 指针纪录 从开始节点(第0个元素)到当前节点能到达的最远距离;
初始值: farthest = A[0]; 很显然,若A[0] = 0, farthest = 0, 在数组元素大于1的情况下,是不能跳到最后一个元素的。
通过一次遍历,算出结果。
贪心思路的原则是, 假定当前指针在第i个, 若farthest 能够跳到最后一个元素,直接结束。
一次遍历的过程就是不停更新farthest与比较的过程 。
a[0] + 0 = farthest(0) 说明不能跳到最后一个元素 能否推出若 a[i] + i = farthest , 则不能跳到最后一个元素
public boolean canJump(int[] A) { // wirte your code here if(A == null || A.length <= 0) { return true; } int farthest = A[0]; for(int i = 0 ; i < A.length - 2; i++) { if(A[i] + i > farthest ) { farthest = A[i] + i; } if(farthest >= A.length - 1) { return true; } if(farthest == i) { return false; } } return farthest >= A.length - 1; }