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
.
对于题目一,思路很简单,贪心,只需要时刻计算前位置和当前位置所能跳的最远长度,并始终和n作比较就可以:
1,若在任意pos位置出现maxstep为0的情况,则说明无法继续向前移动,返回false
2.若在任意pos位置出现maxstep+pos>=n说明可以完成最后一跳,返回true
代码如下:
class Solution { public: bool canJump(int A[], int n) { if(n==0||n==1){ return true; } int maxstep=A[0]; for(int i=1;i<n;i++){ if(maxstep==0) return false; maxstep--; if(maxstep<A[i]){ maxstep=A[i]; } if(maxstep+i>=n-1){ return true; } } } };
struct curinfo{ int pos; int jumpNo; int maxStep; curinfo (int p,int j,int m):pos(p),jumpNo(j),maxStep(m){}; curinfo (const curinfo &c):pos(c.pos),jumpNo(c.jumpNo),maxStep(c.maxStep){}; curinfo & operator= (const curinfo &c){ if(this!=&c){ pos=c.pos; jumpNo=c.jumpNo; maxStep=c.jumpNo; } return *this; }; }; class Solution{ public: int jump(int A[],int n){ if(n<=1) return 0; curinfo cs(0,0,A[0]); queue <curinfo> bfsQueue; bfsQueue.push(cs); while(!bfsQueue.empty()){ cs=bfsQueue.front(); bfsQueue.pop(); for(int i=1;i<=cs.maxStep;i++){ if(cs.pos+i>=n-1) return cs.jumpNo+1; else{ bfsQueue.push(cs.pos+i,jumpNo+1,A[cs.pos+i]); } } } return -1; } };
/* * We use "last" to keep track of the maximum distance that has been reached * by using the minimum steps "ret", whereas "curr" is the maximum distance * that can be reached by using "ret+1" steps. Thus, * curr = max(i+A[i]) where 0 <= i <= last. */ class Solution { public: int jump(int A[], int n) { int ret = 0;//当前跳数 int last = 0;//上一跳可达最远距离 int curr = 0;//当前一跳可达最远距 for (int i = 0; i < n; ++i) { //无法向前继跳直接返回 if(i>curr){ return -1; } //需要进行下次跳跃,则更新last和当执行的跳数ret if (i > last) { last = curr; ++ret; } //记录当前可达的最远点 curr = max(curr, i+A[i]); } return ret; } };