Leetcode jump Game

OpenSoucre發表於2014-07-04

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], return false.

題目的意思是:給出一維非負元素的陣列,每個元素代表從該元素位置能跳得最遠距離。假設初始位置在第一個元素,現在根據輸入陣列判斷是否能跳到陣列的末尾

簡單的貪心演算法,每次記錄當前跳得最遠的位置。

如果當前最遠的位置的陣列到達陣列的尾端,程式返回true

如果當前最遠的位置不能達尾端,而且又不能向前移動的時候,認為不能到達終點,程式返回false

 

class Solution {
public:
    bool canJump(int A[], int n) {
        int maxPos = 0;
        for(int i = 0 ; i < n; ++ i){
            if(maxPos < i) return false;
            if(maxPos >= n-1) return true;
            if(maxPos < A[i]+i) maxPos = A[i]+i;
        }
        return true;
    }
};

 

 

 

相關文章