LeetCode Q 45 - Jump Game II
Given an array of non-negative integers, you are initially positioned at the first index of the array.
Each element in the array represents your maximum jump length at that position.
Your goal is to reach the last index in the minimum number of jumps.
Example: Input: [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.
Note: You can assume that you can always reach the last index.
Solution
Code:
public int jump(int[] nums) {
int curEnd = 0; // farthest distance we can reach in one interation
int curFarthest = 0; // farthest distance we can reach so far
int steps = 0;
// i < nums.length - 1, since we want to calculate the steps to reach the last point, so we don't need to make jumps at last point
for (int i = 0; i < nums.length - 1; i++) {
curFarthest = Math.max(curFarthest, nums[i] + i);
if (i == curEnd) {
curEnd = curFarthest; steps++;
}
}
return steps;
}