新农上路
- 积分
- 90
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-1-18
- 最后登录
- 1970-1-1
|
I prefer the method of Code Ganker
http://blog.csdn.net/linhuanmars/article/details/21356187
"假设当前步数是step, 当走到超过step-1步最远的位置时,说明step-1不能到达当前一步,我们就可以更新步数,将step+1。时间复杂度仍然是O(n),空间复杂度也是O(1)"
int jump(int A[], int n) {
if(A==NULL || n<=0) return 0;
int max_reachable_idx = 0, idx_reachable_min_steps = 0, min_steps=0;
for(int i=0; i<n; i++){
if(i > idx_reachable_min_steps){
// current position is unreachable by previously computed minimal steps
// so update min_steps, also update the furthest reachable position
min_steps++;
idx_reachable_min_steps = max_reachable_idx;
}
max_reachable_idx = max(A[ i ]+i, max_reachable_idx);
}
return min_steps;
} |
|