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;
        }
    }
  • 相关阅读:
    导入别人的flex项目出现的问题
    HTTP通信原理
    java 代码的细节优化
    跨服务器之间的session共享
    spring整合hibernate配置文件
    java中时间类型的问题
    Hibernate注解映射sequence时出现无序增长问题+hibernate 映射 oracle ID自动增长:
    并发处理方案 个人总结
    MsSqlserver 查看锁表与解锁
    c# CTS 基础数据类型笔记
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4561832.html
Copyright © 2011-2022 走看看