题目:
思路:
注意和跳跃游戏【55】不同的是,题目保证可以跳到nums[n-1];那么每次跳到最大即可
代码:
public class LeetCode45 {
public static int jump(int[] nums) {
int jumps = 0;
int currentEnd = 0;
int farthest = 0;
for(int i = 0;i < nums.length - 1; i++){ // 到达nums[length-1] 就已经到了,没必要再往后走了,再走就多了,如 {2,3,0,1,1}, 走到最后一个1再加jumps就多了
farthest = Math.max(farthest,i + nums[i]);
if(i == currentEnd){
jumps++;
currentEnd = farthest;
}
}
return jumps;
}
public static void main(String[] args) {
int[] nums = new int[] {2,3,0,1,1};
System.out.println(jump(nums));
}
}