zoukankan      html  css  js  c++  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.)

    参考:

    水中的鱼: [LeetCode] Jump Game II 解题报告

    [解题思路]
    二指针问题,最大覆盖区间。
    从左往右扫描,维护一个覆盖区间,每扫过一个元素,就重新计算覆盖区间的边界。比如,开始时区间[start, end], 遍历A数组的过程中,不断计算A[i]+i最大值(即从i坐标开始最大的覆盖坐标),并设置这个最大覆盖坐标为新的end边界。而新的start边界则为原end+1。不断循环,直到end> n.

    public class Solution {
        public int jump(int[] A) {
            if(A == null){
                return 0;
            }
            int len = A.length;
            if(len == 0 || len == 1){
                return 0;
            }
            
            int cur = 0;
            int next = 0;
            int ret = 0;
            
            for(int i = 0; i < len; i++){
                if(i > cur){
                    cur = next;
                    ret++;
                }
                next = Math.max(next, i + A[i]);
            }
            return ret;
        }
    }
    public class Solution {
        public int jump(int[] A) {
            int start = 0;
            int end = 0;
            int count = 0;
            int len = A.length;
            if(len == 1) return 0;
            
            while(end < len){
                int max = 0;
                count++;
                for(int i = start; i <=end; i++){
                    if(A[i] +i >= len-1){
                        return count;
                    }
                    
                    if(A[i]+i > max){
                        max = A[i]+i;
                    }
                }
                
                start = end + 1;
                end = max;
            }
            
            return count;
        }
    }
  • 相关阅读:
    mingw-gcc-9.0.1-i686-posix-sjlj-201903
    MSYS 编译 nginx rtmp-module
    MinGW GCC 8.3.1 2019年2月23日 出炉啦
    城市区号SQL
    HCN网络技术实验指南2
    HCN网络技术实验指南1
    CCNA实验攻略1:配置Cisco交换机
    HCDA-7-配置ssh远程管理
    HCDA-6-配置telnet远程管理
    4.1 子网划分基础
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3539134.html
Copyright © 2011-2022 走看看