LeetCode 跳躍遊戲I&II(貪心算法)

55. 跳躍遊戲

代碼(C語言):

int max(int a,int b){
    return a>b?a:b;
}
bool canJump(int* nums, int numsSize){
    int farthest=0;
    for(int i=0;i<numsSize-1;i++){
        farthest=max(farthest,i+nums[i]);//求能跳到的最遠距離
        if(farthest<=i)return false;//如果最遠能跳到的距離剛好爲當前位置,說明當前位置上的值爲0,接下啦只能原地跳動
    }
    return farthest>=(numsSize-1)?1:0;//最遠能跳到的距離超過或等於最後一個位置,返回true
}

45. 跳躍遊戲 II

代碼(C語言):

int max(int a,int b){
    return a>b?a:b;
}
int jump(int* nums, int numsSize){
    int farthest=0,end=0,step=0;
    for(int i=0;i<numsSize-1;i++){
        farthest=max(farthest,nums[i]+i);
        if(end==i){//每次走到end位置開始跳一次,這一次跳躍可以跨越的最遠距離爲farthest
            step++;
            end=farthest;
        }
    }
    return step;
}

【學習資料】

作者:labuladong  公衆號:labuladong  Github網站:https://github.com/labuladong/fucking-algorithm

強烈推薦給大家這位作者寫的算法題解,把問題講得很清楚,很透徹!!裏面的題目主要來源於LeetCode,涵蓋了很多經典的題型。

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章