LeetCode #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.

数组每个数字表示从当前位置可以跳的最大步数,求最少需要跳几次可以到达最后一个元素。

class Solution {
public:
    int jump(vector<int>& nums) {
        int result=0;
        int pre=0; //上一次跳跃的最大下标
        int cur=0; //当前跳跃的最大下标
        //当前最大下标只要超过最后一个元素,说明可以到达最后一个元素
        while(cur<nums.size()-1)
        {
            result++;
            int i=pre;
            pre=cur;
            //依次遍历[pre,cur]中的所有元素用来更新cur
            //但是更新过程中cur会改变,所以先让i保存pre的值,pre保存cur的值
            for(;i<=pre;i++) cur=max(i+nums[i],cur);
        }
        return result;
    }
};

猜你喜欢

转载自blog.csdn.net/LawFile/article/details/86655471