(java)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.)

Note:

You can assume that you can always reach the last index.

思路:ret:代表当前所需的jump数

CURCH:代表从0开始经过ret次jump之后所能到达的最高楼

CURMAX:代表从0 ~i这i+1A元素中所能达到的最高楼

循环遍历,如果i>CURCH说明当前的楼层经过ret此jump之后还是到达不了。需要ret++,CURCH=CURMAX,

每次迭代CURMAX=MAX(CURMAX,nums[i]+i);

代码如下(已通过leetcode)

public class Solution {
public int jump(int[] nums) {
int n = nums.length;
int ret = 0;
       int curMax = 0;
       int curRch = 0;
       for(int i = 0; i < n; i ++)
       {
           if(curRch < i)
           {
               ret ++;
               curRch = curMax;
           }
           curMax = Math.max(curMax, nums[i]+i);
       }
       return ret;


}
}

你可能感兴趣的:((java)Jump Game II)