Problem
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 =
A =
[2,3,1,1,4]
, return true
.
A =
[3,2,1,0,4]
, return false
.Code
bool canJump(int A[], int n) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(n < 2) return true; int r1 = 0; int r2 = 1; while(r1 < r2){ int rmax = r1; for(int i = r1; i < r2; ++i){ if(rmax < i + A[i]) rmax = i + A[i]; if(rmax >= n - 1) return true; } r1 = r2; r2 = rmax + 1; } return false; }
No comments:
Post a Comment