【LeetCode】45. Jump Game II(C++)

本文介绍了一个经典的算法问题“跳远游戏II”,目标是从数组起始位置到达末尾,每一步的跳跃长度由当前位置的数值决定,挑战在于找到达到目标所需的最小跳跃次数。文章详细解释了如何运用广度优先搜索(BFS)思想解决此问题,通过逐步扩展跳跃范围,最终确定最短路径。

摘要生成于 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.
Example:

Input: [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.

Note:

  • You can assume that you can always reach the last index.

理解:

本题要求寻找到从起点到终点的最少跳数。

实现:

使用BFS的思想,从当前位置可以跳到下一步的范围可以确定,从下一步的范围内的位置可以跳到下下一步的范围也可以确定,因此可以每次根据当前的范围判断下一步的范围。
虽然题里给出的是总是可达的,这里还是给出一种通用的方法吧,并不假设总是可达的。

class Solution {
public:
	int jump(vector<int>& nums) {
		if (nums.size() == 1) return 0;
		int step = 0;
		int left = 0, right = 0;
		int maxEnd = 0;
		while (right<nums.size() - 1) {
			++step;
			for (int i = left; i <= right; ++i) {
				if (i + nums[i] >= nums.size() - 1) return step;
				maxEnd = max(maxEnd, nums[i] + i);
			}
			if (maxEnd == right)
				break;
			left = right + 1;
			right = maxEnd;
		}
		return -1;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值