[LeetCode-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.)

思路:维护一个可以到达的最大值,每当超过这个值的时候 步数加一

代码:

public class Solution {
    public int jump(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        
        int max = 0 ; // 最远能到达的位置
        int lastMax = 0 ;  // 上一次的最远距离
        int step = 0 ; // 需要的步数
        
        for(int i = 0 ;i < nums.length; i++){
            
            if(i > lastMax){
                lastMax = max;
                step++;
            }
            max = Math.max(max, i + nums[i]);
        }
        
        return step;
    }
}

 LeetCode中这道题默认了 一定可以达到最后,如果去掉这个默认,需要在循环的时候和最后加入判断

  

public class Solution {
    public int jump(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        
        int max = 0 ; // 最远能到达的位置
        int lastMax = 0 ;  // 上一次的最远距离
        int step = 0 ; // 需要的步数
        
        for(int i = 0 ; i <= max && i < nums.length; i++){
            
            if(i > lastMax){
                lastMax = max;
                step++;
            }
            max = Math.max(max, i + nums[i]);
        }
        if(max < nums.length-1)  
            return 0;
        return step;
    }
}
原文地址:https://www.cnblogs.com/TinyBobo/p/4561832.html