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;
        }
    }
  • 相关阅读:
    Vue数据绑定和响应式原理
    JavaScript实现MVVM之我就是想监测一个普通对象的变化
    缓存的理解
    理解promise 02
    线段与线段的交点
    线段与线段交点的推导公式
    promise你懂了吗?
    wx import require的理解
    webgl example1
    sublime2常用插件
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3539134.html
Copyright © 2011-2022 走看看