45. Jump Game II

problem description

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.

algorithm thought

一次遍历解决问题,第一步能走到的地方就是nums[0],每到一个地方,确定当前位置能走到的最大值。在一步走完之后,确定下一个最大能走到的范围。

code

class Solution {
public:
    int jump(vector<int>& nums) {
        if(nums.size()<2)
            return 0;
        int res=1;
        int maxstep=nums[0];
        int tmpstep=nums[0];
        for(int i=1;i<nums.size()-1;++i){
            tmpstep=max(tmpstep,i+nums[i]);
            if(i==maxstep){
                res++;
                maxstep=tmpstep;
            }
        }
        return res;
    }
};

algorithm analysis

一次遍历数组,时间复杂度O(n)

Last updated