Jump Game II
ID: 45
Input: nums = [2,3,1,1,4]
Output: 2
Explanation: The minimum number of jumps to reach the last index is 2.
Jump 1 step from index 0 to 1, then 3 steps to the last index.Idea
Code
public int jump(int[] nums) {
if(nums.length==1){
return 0;
}
if(nums[0]>=nums.length-1){
return 1;
}
int step = 0;
int i = 1;
int currMax = nums[0];
int max = nums[0];
while(i<=currMax && i<nums.length){
max = Math.max(max, i+nums[i]);
if(i==currMax || i==nums.length-1){
step++;
currMax = max;
}
i++;
}
return step;
}Last updated