leetCode练习(55)

题目:Jump Game

难度:medium

问题描述:

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.

Determine if you are able to reach the last index.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

解题思路:

方法一:

使用了动态规划方法,依次计算第n、n-1、n-2块石头能否达到。第I块石头能否到达取决于第(I+1)到第(I+nums[i])块石头间是否有一块能到达,如果有,那第I块石头也就能到达。这个方法可以算出每一块石头的Boolean值,但是提交时超时啦~ 但我认为仍是一个非常高效的方法,具体代码如下:

	boolean[] cap;
	public boolean canJump(int[] nums) {
        cap=new boolean[nums.length];
        for(int i=nums.length-1;i>=0;i--){
        	cap[i]=canget(nums,i);
        }
        return cap[0];
    }
	public boolean canget(int[]nums,int steps){
		if(steps+nums[steps]>=nums.length-1){
			return true;
		}
		for(int i=nums[steps];i>0;i--){
			if(cap[steps+i]==true){
				return true;
			}
		}
		return false;
	}

方法二:

使用了greedy 贪心算法,在第I块石头上,则下一次需要跳的步数next取决于MAX((1+nums[I+1]),,,,,,,,,,(nums[i]+nums[I+1])),保证每次可能走得最远。但这样是否能保证Boolean的正确性我表示怀疑。但也只有这样我才能提交通过哈~具体代码如下:

public static boolean canJump2(int[] nums) {
		int len=nums.length;
		int index=0;	//当前位置
		int temp=0; 
		int next=0;
		int laststep=len-1;
		if(len==1){
			return true;
		}
        while(index<len-1){
        	temp=0;
        	next=0;
        	if(index+nums[index]>=len-1){
        		return true;
        	}
        	if(laststep==0){
        		break;
        	}
        	for(int i=1;i<=nums[index];i++){
        		if(i+nums[index+i]>temp){
        			next=i;
        			temp=i+nums[index+i];
        		}
        	}
        	index+=next;
        	laststep--;
        }
        return false;
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值