LeetCode 45. 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.

错了好多次,终于AC了!
VBOMnA.jpg

解题思路:
  • 模拟版(AC):最简单有效的办法就是模拟跳的过程,也就是模拟你用眼睛看那个示例的答案是怎么来的那个过程。具体细节见代码。
int jump(vector<int>& nums){
	int n = nums.size();
	if(n == 0 || n == 1)
		return 0;
	
	int maxPos = 0;      // 下一跳能跳到的最远的位置
	int currMax = 0;     // 这一跳能到达的最远的位置
	int ans = 0;         // 需要跳的步数
	// 模拟跳的过程
	for(int i = 0;i < n; i++) {
		maxPos = max(maxPos, nums[i]+i);  
		if(i < currMax)   // 这里不能等于,因为maxPos已经更新到i了,当i == currPos时就必须进行下一跳的抉择了 
			continue;
		else{
			ans++;
			currMax = maxPos;
			if(currMax >= n-1)   // 如果能跳到最后就可以直接退出了
				break;
		}
	}
	return ans;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值