【leetcode】45. Jump Game II 非負陣列的最少跳躍步數

knzeus發表於2019-05-14

1. 題目

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.

For example:
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.

2. 思路

第一個節點必須要進入,每次進入一個起點i之後,下一步的落點可以是[i+1, i+nums[i]],找到這個範圍內的可以跳躍最遠的點作為下一步。迴圈直到跳躍到最後。

3. 程式碼

耗時:13ms

class Solution {
public:
    // 當做到第i步時,此時最大可以跳躍到的點時i+a[i]; 
    // 下一步找到[i, i+a[i]]之間的最大可跳躍點, 下一步選擇這個最大點
    // 迴圈往復直到到最後一個點
    int jump(vector<int>& nums) {
        int sz = nums.size();
        if (sz <= 1) { return 0; }
        int k = 0;
        int i = 0;
        int i_max = 0;
        while (i < sz - 1) {
            k++;
            int i_max = i + nums[i]; // 當前跳躍段的起點
            if (i_max >= sz - 1) { break; }
            int j_max = -1;
            int j_max_idx = -1;
            for (int j = i + 1; j <= i_max && j < sz; j++) { // 選擇[i, i+nums[i]]段內的最大跳躍點作為下一點
                int tmp_max = j + nums[j];
                if (tmp_max > j_max) {
                    j_max = tmp_max;
                    j_max_idx = j;
                }
            }
            i = j_max_idx;
        }
        
        return k;
    }
};

相關文章