44. 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.
For example:
Given array A = [2,3,1,1,4]
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.)
---
叨唠出神经病了快!
public class Solution { public int jump(int[] A) { int count = 0; int reachedLen = 0; //之前通过最优跳法能到达的位置,我实际跳过的 int possibleLen = 0; //目前能到的最远位置,还没实际跳,但是可以从左边跳到 for (int i = 0; i < A.length; i++) { if (i > reachedLen) { // 我现在在i, 已经超过之前的用最优跳法到达的位置reachedLen // 我该跳新的一步了,跳到能跳到的最远位置 // 那个位置就是nextMax, 也就是目前我能到的最远位置 // 由于我跳了一步,所以步数+1 reachedLen = possibleLen; count++; if(reachedLen == A.length-1) // Done! return count; } // nextMax是当前能到的最远位置 // 有可能,是之前跳的,从左边的点跳了好几部,已经可以跳到i的右边,即nextMax, // 还可能,是从当前位置跳的,跳到的能跳到的最远位置,就是i+A[i] possibleLen = Math.max(possibleLen,A[i] + i); } return count; } }
浙公网安备 33010602011771号