class Solution{
public:
int jump(int A[], int n){
if(n < 2){ //when less than two elements, no need to jump
return 0;
}
int ll = 0, rr = 0, step = 0, lastrr = 0;
while(true){
int tmpf = -1, tmpn = n * 2;
for(int i = ll; i <= rr; ++i){ //jump as far as possible
tmpf = max(tmpf, A[i] + i);
}
if(tmpf > rr){ //update farthest distance
rr = tmpf;
step++;
}
if(ll < rr){ //jump at least one step a time
++ll;
}
if(rr >= n - 1){
return step;
}
}
return -1;
}
};
leetcode jumpgame 2
最新推荐文章于 2022-05-06 17:05:28 发布