(Java)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.

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.)

Note:
You can assume that you can always reach the last index.


这道题我刚开始用的是递归的想法,从后往前逐步计算。比如要计算跳到第n个点的次数f(n),那么就等于在n点前面的一跳可以到n点的若干个点以m表示,为min{f(m)} + 1,依次递归,已经计算过的用一个数组存储,防止重复计算。然而这样会栈溢出。纪念代码如下

public class Solution {
    public int jump(int[] nums) {
        return f(nums, nums.length-1);
    }
    
    public int f(int[] array, int num){
		int[] results = new int[num];
		for(int i = 0; i < num; i ++){
			results[i] = -1;
		}
		int result =  f(array, num, results);
		return result;
	}
	
	public int f(int[] array, int num, int[] results){
    	
    	if(num == 0)
    		return 0;
    	int min = Integer.MAX_VALUE;
    	for(int i = num - 1; i >= 0; i--){
    		if(array[i] + i >= num){
    			int temp;
    			if(results[i] == -1){
    				results[i] = f(array, i , results);
    				temp = 1 + results[i];
    			}else{
    				temp = results[i] + 1;
    			}
    			if(min > temp){
    				min = temp;
    			}
    		}
    	}
   		return min;

    }
}

于是经过改进,从前往后进行遍历数组计算,用一个数组times[]记录当前遍历情况下跳到该点的最少跳数,当第一次跳到最后一个节点时,结束。注意,当nums[]数组中后一个数比前一个数小的时候,可以忽略其后的数,其实这里可以扩大范围,就是后面的数与最后遍历的有贡献的数的差值大于其距离时,那么这个数也是无贡献的。代码如下:


public class Solution {
   public int jump(int[] nums) {

        if(nums.length <2)
            return 0;
    	

    	int length = nums.length;
    	int times[] = new int[length];
    	for(int i = 0; i < length; i++){
    		times[i] = -1;
    	}
    	times[0] = 0;
    	for(int i = 0; i < length; i++){
    		if(i > 0){
    			if(nums[i] < nums[i-1]){<span style="white-space:pre">		</span>//忽略无贡献的数
    				continue;
    			}
    		}
    		for(int j = 1; j <= nums[i]; j++){
    			if(times[i+j] == -1){
    				times[i +j] = times[i] + 1;
    			}else if( times[i+j] > times[i] + 1){
    				times[i+j] = times[i] + 1;
    			}
    			
    			if(i + j == length - 1){
    				return times[length-1];
    			}
    		}
    	}
        return -1;
    
    }
}


后来在其他人的博客上看到另一种解法,十分巧妙,速度更快,地址是http://www.cnblogs.com/ganganloveu/p/3761715.html


主要思路是

ret:目前为止的jump数

curRch:从A[0]进行ret次jump之后达到的最大范围

curMax:从0~i这i+1个A元素中能达到的最大范围

当curRch < i,说明ret次jump已经不足以覆盖当前第i个元素,因此需要增加一次jump,使之达到记录的curMax。


最后我想如果存在不能到达的情况,那么遍历的时候会出现i > cuRch的情况,如果出现直接返回-1即可。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值