45. Jump Game II

30 篇文章 0 订阅

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.





刚开始想用DP,但是要循环判断前面的每一项,复杂度O(n^2),

package l45;

/*
 * 分别对到达该处需要的最小step进行求解
 */
public class CopyOfSolution {
    public int jump(int[] nums) {
        int len = nums.length, cur_min = Integer.MAX_VALUE;
        int[] minReach = new int[len];
        for(int i=0; i<len; i++)
        	minReach[i] = Integer.MAX_VALUE;
        
        minReach[0] = 0;
        for(int i=1; i<len; i++) {
        	//if(cur_min >= minReach[i])	break;
        	for(int j=0; j<i; j++) {
        		if(nums[j] + j >= i) {
        			if(minReach[j]!=Integer.MAX_VALUE && minReach[j]+1<minReach[i]) {
        				minReach[i] = minReach[j]+1;
        			}
        		}
        	}
        }
        
    	return minReach[len-1];
    }
}



考虑到这种解法是:分别对到达该处需要的最小step进行求解,每次都可能会达到末尾,但是不一定是最短的,所以换种perspective考虑,考虑步数一步步增加,并求出最远能到多少,当可以到达末尾,跳出循环即可

*
 * 步数一点一点累加,最远能达到最后即可跳出循环
 */
public class Solution {
    public int jump(int[] nums) {
        int step = 0;
        int curMax = 0, preMax = 0, nextMax = 0;
        if(nums.length == 1)	return 0;
        
        while(true) {
        	step ++;

        	for(int i=preMax; i<=curMax; i++) {
        		if(i+nums[i]>nextMax)	nextMax = i+nums[i];
        	}
        	
        	if(nextMax >= nums.length-1)	return step;
        	
        	preMax = curMax;
        	curMax = nextMax;
        }
    }
}

每个位置只需要遍历一次,所以BFS可以剪枝很多

class Solution(object):
    def jump(self, a):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(a)<=1: return 0
        step = 0
        cur_min, cur_max = 0, 0
        while cur_max<len(a)-1:
            next_max = cur_max+1
            for i in range(cur_min, cur_max+1):
                next_max = max(i+a[i], next_max)
            cur_min, cur_max = cur_max+1, next_max
            step+=1
        return step
    
s=Solution()
print(s.jump([2,3,1,1,4]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值