• LeetCode No45. 跳跃游戏 II


    题目

    给你一个非负整数数组 nums ,你最初位于数组的第一个位置。

    数组中的每个元素代表你在该位置可以跳跃的最大长度。

    你的目标是使用最少的跳跃次数到达数组的最后一个位置。

    假设你总是可以到达数组的最后一个位置。

    示例 1:

    输入: nums = [2,3,1,1,4]
    输出: 2
    解释: 跳到最后一个位置的最小跳跃数是 2。
      从下标为 0 跳到下标为 1 的位置,跳 1 步,然后跳 3 步到达数组的最后一个位置。

    示例 2:

    输入: nums = [2,3,0,1,4]
    输出: 2

    提示:

    1 <= nums.length <= 10^4
    0 <= nums[i] <= 1000

    思路

    典型的贪心题,当前在i,所能到的下一步最大能到 i+nums[i],那么下下一步一定到 i至i+nums[i]中,index+nums[index]最大的位置上。

    AC代码

    点击查看代码
    class Solution {
        public int jump(int[] nums) {
            int n = nums.length;
            int pos = 0;
            int cnt = 0;
            int lastIndex = 0;
            for(int i=0; i<n-1; i++) {
                pos = Math.max(pos, i+nums[i]);
                if( i == lastIndex ) {
                    lastIndex = pos;
                    cnt ++;
                }
            }
            return  cnt;
        }
    }
    
  • 相关阅读:
    redis的间隔性速度慢的问题
    centos增加静态路由
    排查问题的一些基本命令
    laradock
    python之sqlalchemy基本
    ssl证书之certbot
    mysql 多实例
    模块和包
    异步
    WSGI
  • 原文地址:https://www.cnblogs.com/Asimple/p/16290239.html
Copyright © 2020-2023  润新知