2014-10-20 11:23:39 +08:00
|
|
|
// Source : https://oj.leetcode.com/problems/jump-game/
|
|
|
|
// Author : Hao Chen
|
|
|
|
// Date : 2014-06-27
|
|
|
|
|
2014-10-21 10:49:57 +08:00
|
|
|
/**********************************************************************************
|
|
|
|
*
|
|
|
|
* 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.
|
|
|
|
*
|
|
|
|
*
|
|
|
|
**********************************************************************************/
|
|
|
|
|
2014-10-20 11:23:39 +08:00
|
|
|
class Solution {
|
|
|
|
public:
|
|
|
|
bool canJump(int A[], int n) {
|
|
|
|
if (n<=0) return false;
|
|
|
|
|
2014-10-27 22:43:09 +08:00
|
|
|
// the basic idea is traverse array, maintain the most far can go
|
2014-10-20 11:23:39 +08:00
|
|
|
int coverPos=0;
|
2014-10-27 22:43:09 +08:00
|
|
|
// the condition i<=coverPos means traverse all of covered position
|
2014-10-20 11:23:39 +08:00
|
|
|
for(int i=0; i<=coverPos && i<n; i++){
|
|
|
|
|
|
|
|
if (coverPos < A[i] + i){
|
|
|
|
coverPos = A[i] + i;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (coverPos>=n-1){
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
};
|