jump game java_[LeetCode] 55. Jump Game Java

题目:

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.

题意及分析:根据题目要求,数组里的每个元素表示从该位置可以跳出的最远距离,要求问从第一个元素(index=0)开始,能否达到数组的最后一个元素,这里认为最后一个元素为终点。这里是到达,说明超过也行,看下图能更好的理解题意。

c66bf9ebdead4e70083d18ac3913ddde.png

所以这里可以使用贪心算法,计算出某个点时 能够跳出的最大距离(当前的最大值和(当前点+能跳出的最大距离)的较大的值),如果能跳出的最大距离大于最后一个点的位置,那么返回true,能到达;如果到达当前点后,不能在往后跳,那么不能达到最后点,返回false。

代码:

public class Solution {

public boolean canJump(int[] nums) {

if(nums.length<1)

return false;

if(nums.length==1)

return true;

int max=0;//记录到当前点时能到达的最大位置

for(int i=0;i

max=Math.max(max, i+nums[i]);

if(max

// System.out.println(false);

return false;

}

if(max>=(nums.length-1)){

// System.out.println(true);

return true;

}

}

return false;

}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值