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萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章