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

发布了53 篇原创文章 · 获赞 5 · 访问量 8万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章