Jump Game--lintcode

Description

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.

Example

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

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

我的思路:贪心算法。我开始的时候 是用i+=A[i],可是万一跳到数组中值为0的位置,就需要另外判断。是返回false,还是跳的步数少一点。很麻烦。都用到两个for循环了。网上搜索了一下。

参考网址:http://blog.csdn.net/linhuanmars/article/details/21354751

public boolean canJump(int[] A) {  
    if(A==null || A.length==0)  
        return false;  
    int reach = 0;  
    for(int i=0;i<=reach&&i<A.length;i++)  
    {  
        reach = Math.max(A[i]+i,reach);  
    }  
    if(reach<A.length-1)  
        return false;  
    return true;  
}  

这里 i是一个一个加的,不是跳着的。
以2,3,1,1,4为例:
i=0 reach=max(0+2,0)=2;
i=1 reach=max(1+3,2)=4;
i=2 reach=max(2+1,4)=4;
i=3 reach=max(3+1,4)=4;
i=4 reach=max(4+4,4)=8.
返回true.
以3,2,1,0,4为例:
i=0, reach=max(0+3,0)=3;
i=1 reach=max(1+2,3)=3;
i=2 reach=max(2+1,3)=3;
i=3 reach=max(3+0,3)=3.
此时i<=reach。所以跳出for循环。而reach

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值