45. Jump Game II

Problem:

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.

思路

采用BFS算法。每次计算出能到达的最远距离reach,则下一次的end为reach,start为上一次的end+1,保存能够到达的区域[start, end],然后判断是否能到达终点。

Solution (C++):

int jump(vector<int>& nums) {
    if (nums.empty())  return 0;
    int n = nums.size(), step = 0, start = 0, end = 0, reach;
    
    while (end < n-1) {
        step++;
        reach = end + 1;
        
        for (int i = start; i <= end; ++i) {
            if (i + nums[i] >= n-1)  return step;
            reach = max(reach, i + nums[i]);
        }
        start = end + 1;
        end = reach;
    }
    return step;
}

性能

Runtime: 12 ms  Memory Usage: 10.2 MB

posted @ 2020-02-10 13:50  littledy  阅读(82)  评论(0编辑  收藏  举报