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

思路:

1.Jump Game思路:和求Max Subarray类似,维护一个当前元素能够跳至的最大值,每循环一次更新reach=Math.max(nums[i]+1,reach),当i>reach或i>=nums.length的时候循环终止。最后看循环是否到达了最后,到达最后则返回true,否则,返回false.

2.和Jump Game不同的是,Jump Game II 让求的是跳过全部的元素至少须要几步。这须要维护一个局部变量edge为上一个reach,当i<=reach时,每次仍然通过Math.max(nums[i]+i,reach)获得最大的reach,当i>edge时,仅仅须要更新一个edge为当前reach就可以。并将minStep赋值为minStep+1。最后,当到达最后一个元素的时候说明能够到达最后,范围最少的步骤就可以。

代码:

public int jump(int[] nums)
	{
		int edge=0,reach=0;
		int minStep=0,i=0;
		for(;i<nums.length&&i<=reach;i++)
		{
			if(edge<i)
			{
				edge=reach;
				minStep=minStep+1;
			}
			reach=Math.max(nums[i]+i, reach);
		}
		if(i==nums.length)
			return minStep;
		return -1;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值