思路:
使用两个变量,range是当前最大可以到达的范围,nextRange是下一个可以到达的范围。如果超了当前最大可以到达的范围,就把range更新为nextRange,步数加1。
代码:
class Solution {
public int jump(int[] nums) {
int n = nums.length;
int range = 0;
int nextRange = 0;
int cnt = 0;
for(int i = 0; i < n; i++) {
if(i > range) {
range = nextRange;
cnt++;
}
nextRange = Math.max(nextRange, i + nums[i]);
}
return cnt;
}
}