LeetCode OJ算法题(四十四):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.)

解法:

这题要求调到指定位置需要的最小步数,可以用递归,但是TLE了。

我们可以换一个角度来思考,如果我们知道指定步数能够达到的最远距离,那么只要逐步增加步数,当这个最远距离超过阈值时就返回结果就可以了。

那么接下来的问题就是如何求出指定步数n下能达到的最远距离,不妨设这里距离为f(n)

要在第n步到达f(n),那么n-1步所到达的位置X(n-1),它一定小于等于f(n-1),同理我们有X(n-2)<= f(n-2),因此只要我们在n-2时到达X(n-2),一定可以在第n时到达f(n),所以我们只需求出X(n-2)即可,即在X(n-3)一定的情况下,遍历找到使第n-1步达到最远距离的X(n-2),这样找出来的最远距离就是f(n-1)。

换个说法:已知X(0)=0,f(1)=A[1],找到X(1)使得第2步能到达最远,再以X(1)为基点,找到能使第3步到达最远的X(2),这样找到的X序列即为最优解,在求解的过程中还可以求出f(n)。

public class No44_JumpGameII {
	public static void main(String[] args){
		System.out.println(jump(new int[]{2,3,1,3,1,1,7}));
	}
	public static int jump(int[] A) {
		if(A.length == 1) return 0;
		int ret = 1;
        int furthest = A[0];
        int start = 0;
        while(furthest < A.length-1){
        	int end = start + A[start];
        	for(int i=start+1;i<=end;i++){
        		if(i+A[i]>furthest){
        			furthest = i + A[i];
        			start = i;
        		}
        	}
        	ret++;
        }
        return ret;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值