45. Jump Game II

問題

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.

Your goal is to reach the last index in the minimum number of jumps.

例子

Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Note:
You can assume that you can always reach the last index.

分析

首先考慮dp,空間復(fù)雜度為O(n),時間復(fù)雜度為O(n^2),超時;
再考慮bfs,先列出從起點(diǎn)出發(fā)能跳到的節(jié)點(diǎn),再列出從這些節(jié)點(diǎn)出發(fā)能跳到的節(jié)點(diǎn)......直到跳到終點(diǎn)。記錄bfs的層數(shù)。

要點(diǎn)

dp/dfs

時間復(fù)雜度

O(n)

空間復(fù)雜度

O(1)

代碼

class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() < 2) return 0;
        // i:數(shù)組下標(biāo) level: bfs層數(shù)
        // curRange: 當(dāng)前能跳到的最遠(yuǎn)范圍
        // nextRange: 下一步能跳到的最遠(yuǎn)范圍
        int i = 0, level = 0, curRange = 0, nextRange = 0;
        while (i <= curRange) {
            level++;
            for (; i <= curRange; i++) {
                nextRange = max(nextRange, i + nums[i]);
                if (nextRange >= nums.size() - 1) return level;
            }
            curRange = nextRange;
        }
        return 0;
    }
};

擴(kuò)展

如果問題中數(shù)組的元素表示只能跳的步數(shù)(原題目為能跳的最大步數(shù)),那么可能會有一些節(jié)點(diǎn)會跳不到,但還可以用bfs在O(n)時間內(nèi)解決。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容