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.
For example:
Given array A = [2, 3, 1, 4]
The minimum number of jumps to reach the last index is2. (jump1step from index 0 to 1, then3steps to the last index .)
Https://oj.leetcode.com/problems/jump-game-ii/
Thought 1: I first thought about DP, and pushed forward from the back. The minimum number of steps at the current position is determined by the minimum number of steps within the range it can reach. Therefore, we need to traverse the coverage range and the complexity is slightly higher, it is not an O (n) algorithm, and the visual test times out.
Idea 2: greedy. Maintain several variables, curreach and nextreach, and update nextreach within the range of curreach until the end of curreach is overwritten.
Public class solution {public int jump (INT [] A) {if (a = NULL |. length <2) return 0; int n =. length; int step = 0; int curreach = 0; int nextreach = 0; int I; for (I = 0; I <n ;) {If (curreach> = n-1) break; while (I <= curreach) {nextreach = nextreach> (I + A [I])? Nextreach: (I + A [I]); I ++;} curreach = nextreach; Step ++;} return step;} public static void main (string [] ARGs) {system. out. println (new solution (). jump (New int [] {2, 3, 1, 1, 1, 2, 3 }));}}
Refer:
Http://www.cnblogs.com/lichen782/p/leetcode_Jump_Game_II.html
Http://blog.csdn.net/havenoidea/article/details/11853301