首页 > 其他分享 >45. Jump Game II

45. Jump Game II

时间:2022-11-06 22:56:48浏览次数:40  
标签:II nums int index length Jump maxPosition Game steps

You are given a 0-indexed array of integers nums of length n. You are initially positioned at nums[0].

Each element nums[i] represents the maximum length of a forward jump from index i. In other words, if you are at nums[i], you can jump to any nums[i + j] where:

  • 0 <= j <= nums[i] and
  • i + j < n

Return the minimum number of jumps to reach nums[n - 1]. The test cases are generated such that you can reach nums[n - 1].

 

Example 1:

Input: nums = [2,3,1,1,4]
Output: 2
Explanation: 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.

Example 2:

Input: nums = [2,3,0,1,4]
Output: 2

 

public int jump2(int[] nums) {
int length = nums.length;
int end = 0; // 表示上一步到达的最远位置
int maxPosition = 0; // 表示当前能到达的最远位置
int steps = 0;
for (int i = 0; i < length - 1; i++) {
maxPosition = Math.max(maxPosition, i + nums[i]);
if (i == end) { // 判断如果当前位置到达了上一步能到达的最远位置,说明需要再跳一次了,并且步数steps自增1
end = maxPosition;
steps++;
}
}
return steps;
}

标签:II,nums,int,index,length,Jump,maxPosition,Game,steps
From: https://www.cnblogs.com/MarkLeeBYR/p/16864527.html

相关文章

  • 55. Jump Game
    Youaregivenanintegerarray nums.Youareinitiallypositionedatthearray's firstindex,andeachelementinthearrayrepresentsyourmaximumjumpleng......
  • Palindrome Partitioning II
    https://leetcode.cn/problems/palindrome-partitioning-ii/dp[i]表示s[0..i]切分为回文子串的最小分割次数dp[i]=min(dp[j]+1),如果s[j+1...i]是回文串,j<......
  • 基于gamebased算法的动态频谱访问matlab仿真
    目录一、理论基础二、核心程序三、测试结果一、理论基础随着越来越多的新型无线应用,对频谱资源的需求越来越大。在这种情况下,这是举世公认的认知无线电的出现已经成......
  • pgpool ii在lightdb下的性能测试
    1、从https://www.pgpool.net/下载最新版pgpoolii,如4.3.2。2、假设安装了postgresql或lightdb,百度一搜即可3、解压包,执行./configure &&make&&makeinstall4、修......
  • Codeforces Round #832 (Div. 2) C. Swap Game (博弈论)
    https://codeforces.com/contest/1747/problem/CC.SwapGame题目大意:给定一个长度为n的数组a,每次只要当我想动但是发现a[1]==0的时候我就输了要么就是我每次把a[1]......
  • Google Game Service 接入指南
    前言应用接入Game登录,接入过程中遇到各种卡流程的问题,首次接入Gamev2,发现Gamev2版本的调用时机无法自行控制,并且不能退出当前登录的账户。而旧版gamev1的api提供了退......
  • 关于为什么使用 ascii GBK unicode编码
    关于为什么使用asciiGBKunicode编码由来:大家都知道计算机最早是美国人为了更加便捷的存储和计算数据发明的,但是呢计算机底层都是硬件,只能存储像0101这样的二进制数据,那......
  • k8s结合jumpserver做kubectl权限控制 用户在多个namespaces的访问权限 rbac权限控制
    k8s结合jumpserver做kubectl权限控制用户在多个namespaces的访问权限rbac权限控制 https://www.cnblogs.com/fanfanfanlichun/p/14989454.html  其实这个文章就......
  • 基于gamebased算法的动态频谱访问matlab仿真
    目录一、理论基础二、核心程序三、测试结果一、理论基础随着越来越多的新型无线应用,对频谱资源的需求越来越大。在这种情况下,这是举世公认的认知无线电的出现已经成为......
  • 实例036 字母与ASCII码的转换
      usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usi......