【LeetCode】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.)

题目思路很容易想,对某i,在A(i:i+A[i])范围内寻找最大数,那么这个数就是这次跳跃的目标。这个方法写一个双层循环是很容易实现的,第一层循环0:n,第二层循环A(i:i+A[i])。但是直觉告诉我一定有one pass的方法。

这个方法的关键就是如何在不回溯的情况下找到最大值并继续下一次查找。想通了以后实际上很简单。我们用curr来记录已经找到的可以跳到的最大距离,即curr=i + A[i],i是当前位置即已经走过的距离,A[i]则是可以跳过的距离。用len来记录前一次跳跃所能达到的最大长度,这样当i>len时即标志着进入了新的搜索范围,此时res++,len=curr。

代码如下:

class Solution {
public:
	int jump(int A[], int n) {
		int res(0), len(0), curr(0);
		for (int i = 0; i < n; i++){
			if (i>len){
				len = curr;
				res++;
			}
			curr = max(curr, i + A[i]);
		}
		return res;
	}
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值