BFS solution for reference.
/**
* Breadth first search o(n).
* Map each number in the array to a level,
* where numbers in level i are all the numbers that can be reached in i-1th jump.
* e.g. 2, 3, 1, 1, 4
* level 0: 2
* level 1: 3, 1
* level 2: 1, 4
* The minimum jump is 2.
*/
public class Solution {
public int jump(int[] nums) {
if (nums.length < 2) return 0;
int i = 1, lvl = 1, maxReach = nums[0], nextMax = 0;
while (maxReach < nums.length-1) {
for (; i<=maxReach; i++)
// find the max reach of a level
// there always exists a i+nums[i] >= maxReach (*)
// so we can use nextMax to record the maxReach
nextMax = Math.max(i+nums[i], nextMax);
// maxReach doesn't move forward after scanning a level
// which means we can never jump to the end
if (maxReach == nextMax) return Integer.MAX_VALUE;
maxReach = nextMax;
lvl++;
}
return lvl;
}
}