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.

Example:

Input: [2,3,1,1,4]
Output: 2
Explanation: 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.

題目假定所有input都能到達最後一個element,我們可以利用greedy method,搭配紀錄前一步能抵達的最遠位置還有目前能抵達的最遠位置。按順序掃描input array裡所有位置起跳能到達的最遠位置紀錄於curReach,如果當前position是上一步能抵達的最遠位置,那麼就更新上一步起跳能抵達的最遠位置還有當前步數。

// Greedy Method
int jump(vector<int>& nums) { // time: O(n); space: O(1)
    int res = 0, n = nums.size(), last = 0, curReach = 0;
    for (int i = 0; i < n - 1; ++i) {
        curReach = max(curReach, i + nums[i]);
        if (i == last) {
            last = curReach;
            ++res;
            if (curReach >= n - 1) break;
        }
    }
    return res;
}
// Greedy
int jump(vector<int>& nums) { // time: O(n); space: O(1)
    int n = nums.size(), reach = 0, idx = 0, last = 0, res = 0;
    while (idx < n - 1 && idx <= reach) {
        reach = max(reach, idx + nums[idx]);
        if (idx == last) {
            last = reach;
            ++res;
            if (reach >= n - 1) break;
        }
        ++idx;
    }
    return res;
}
55. Jump Game

Last updated

Was this helpful?