LeetCode Jump Game II

本文介绍了解决LeetCode上Jump Game II问题的方法。该问题是求解到达数组最后一个元素所需的最少跳跃次数。通过一次遍历数组并使用三个变量记录最大跳跃范围、可达最远距离及步骤数,实现O(n)的时间复杂度与O(1)的空间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原题链接在这里: https://leetcode.com/problems/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.)

题解:

这是的Jump Game进阶版题目。求能跳到最后一个元素的最小步数。

采用了Jump Game中的Method 2. maxJump是维护的当前能跳到的最大位置,maxReach是指从之前的点能reach到得最远位置。

当i 大于之前点能碰到的最大位置时,就需要跳一步,并把maxReach更新为maxJump.

最后返回若是maxJump能到最后一个元素,就返回step, 若是到不了,就说明根本走不到最后一步,返回0.

Time Complexity: O(n). Space: O(1).

AC Java:

 1 public class Solution {
 2     public int jump(int[] nums) {
 3         if(nums == null || nums.length == 0){
 4             return 0;
 5         }
 6         int maxJump = 0;
 7         int maxReach = 0;
 8         int step = 0;
 9         for(int i = 0; i< nums.length && i<=maxJump; i++){
10             if(i>maxReach){
11                 step++;
12                 maxReach = maxJump;
13             }
14             maxJump = Math.max(maxJump, nums[i] + i);
15         }
16         return maxJump<nums.length-1 ? 0:step;
17     }
18 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4834079.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值