Jump Game

Jump Game


今天是一道有關(guān)貪婪算法的題目,來(lái)自LeetCode#55,難度為Medium,Acceptance為27.2%

題目如下

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.

思路如下

該題中只需要求能不能到達(dá)最后一個(gè)元素,而不必求最少的步數(shù),相對(duì)較為簡(jiǎn)單。只要按照貪婪算法,每到下一個(gè)元素求由該元素開始的最遠(yuǎn)的元素i + nums[i]即可。

代碼如下

java版
public class Solution {
    public boolean canJump(int[] nums) {
        int reach = 0;
        for(int i = 0; i <= reach && reach < nums.length; i++) {
            reach = Math.max(reach, i + nums[i]);
        }
        return reach >= nums.length - 1;
    }
}
C++版
bool canJump(int A[], int n) {
    int i = 0;
    for (int reach = 0; i < n && i <= reach; ++i)
        reach = max(i + A[i], reach);
    return i == n;
}

關(guān)注我
該公眾號(hào)會(huì)每天推送常見面試題,包括解題思路是代碼,希望對(duì)找工作的同學(xué)有所幫助

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容