1. 程式人生 > >Jump-Game

Jump-Game

題目描述

  • Jump Game

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], returnfalse.

題目大意

給定一個非負整數陣列,最初的位置是該陣列的第一個索引位置。
陣列中的每個元素值表示該位置的最大跳躍長度。
確定是否能夠達到最後一個索引位置。
例如:
a=[2,3,1,1,4],返回 true。
A=[3,2,1,0,4],返回 false。

思路

定義一個max_reach變數,表示最大能夠達到的位置,然後遍歷陣列元素,每次到達一個索引位置後,判斷大年索引位置加上當前索引位置的元素的值A[ i ] + i是否大於max_reach,如果大於就更新max_reach的值。
陣列元素遍歷的一個條件是max_reach >= i,表示此時能夠調到i處。
最後判斷,max_reach >= n-1

表示能夠調到最後一個位置。

程式碼

#include<iostream>
using namespace std;

bool canJump(int A[], int n)
{
    int max_reach = 0; // max標記能跳到的最遠處

    // max_reach>=i表示此時能跳到i處,
    // 0<=i<n表示掃描所有能到達的點,在改點處能跳到的最遠處
    for(int i=0; i<n && max_reach>=i; i++)
        if(max_reach < A[i]+i)max_reach = A[i]+i;

    // 如果最後跳的最遠的結果大於等於n-1,
    // 那麼滿足能跳到最後。
    if(max_reach < n-1)return false;

    return true;

}

int main()
{
    int A[] = {2, 3, 1, 1, 4};
    if(canJump(A, 5))
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
    int B[] = {3, 2, 1, 0, 4};
    if(canJump(B, 5))
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
    return 0;
}

執行結果

以上。


版權宣告:本文為博主原創文章,轉載請註明出處。
個人部落格地址:https://yangyuanlin.club
歡迎來踩~~~~