zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    1-7周成绩总结
    1-6周成绩总结
    第七周学习笔记
    前五周测验成绩总结
    第六周学习笔记
    第五周学习笔记
    2018-2019-2 20189206 Python3学习
    2018-2019-2 20189206 安全工具的学习
    2018-2019-2 20189206 《网络攻防实践》 第一周作业
    2018-2019-1 20189206 《Linux内核原理与分析》第九周作业
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4561832.html
Copyright © 2011-2022 走看看