jump-game-ii

package easy.greedy;

import org.junit.Test;

public class Jump {
	int minstep =100000;
	 public int jump(int[] A) {
	       int step = 0 ;
	       if(A.length==1)return 0;
	       jumping(A, step, 0, 0);
	       return minstep;
	 }
	 
	 public void jumping(int[] A,int step,int location,int length) {
		 if(location>=A.length-1) {
			 if(minstep>step)minstep=step;
			 return;
		 }
		 
		 
		 //从这个位置跳
		 if(length>=location) {
			 if(length<=(location+A[location])) {
				 length = location+A[location];
			 }
			 //可以走
			 int chance = A[location];
			 while(chance>0) {
				 location = location + chance;
				 step++;//从location跳出去
				 jumping(A, step, location, length);
				 step--;
				 location = location - chance;
				 chance--;
			 }
		 }
	 }
	 @Test
	 public void test() {
		 int[] A= {2,3,1,1,4,5,8,1,1};
		 System.out.println(jump(A));
	 }
}

这个算法复杂度太大,必须简化

这种方法是简化的方法:逻辑很清晰,即遍历数组,如果超出上一步能达到的最大值,就跳,并把当前所能达到的最大值赋给上一步能达到的最大值,代表跳了一步。如果最后上一步能达到数组最后一位,返回结果,否则,返回-1

public class Solution {
 public int jump(int[] A) {
		int step = 0;
		if (A.length == 1)
			return 0;
		int curFarest = 0;//当前能跳的最远的地方
		int lastFarest = 0;//上一步能跳的最远的地方
		for (int i = 0; i < A.length; i++) {
			if(i>lastFarest) {
				step++;
				lastFarest = curFarest;
			}
			curFarest = i+A[i]>curFarest?i+A[i]:curFarest;
		}
		if(lastFarest>=A.length-1) {
			return step;
		}
		return -1;
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值