【LeetCode】114.Jump Game II

题目描述(Hard)

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.

题目链接

https://leetcode.com/problems/jump-game-ii/description/

Example 1:

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.

算法分析

贪心法,找到每一步所能到达的最远距离。

方法一:每次在当前区域中,寻找一个当前步所覆盖的最大区域;

方法二:寻找下一步的最远距离,如果当前位置大于最远距离,则进行跳到下一步的最远距离。

提交代码(方法一):

class Solution {
public:
    int jump(vector<int>& nums) {
        int step = 0;
        int left = 0;
        int right = 0;
        if (nums.size() == 1) return 0;
        
        while(left <= right) {
            ++ step;
            int old_right = right;
            for (int i = left; i <= old_right; ++i) {
                int new_right = i + nums[i];
                if (new_right >= nums.size() - 1) return step;
                if (new_right > right) right = new_right;
            }
            
            left = old_right + 1;
        }
        
        return 0;
    }
};

提交代码(方法二):

class Solution {
public:
    int jump(vector<int>& nums) {
        //步数,下一步到达的最远距离,当前最远距离
        int step = 0, cur = 0, last = 0;
        
        for (int i = 0; i < nums.size(); ++i) {
            if (i > last)
            {
                last = cur;
                ++step;
            }
            
            cur = max(cur, i + nums[i]);
        }
        
        return step;
    }
};

猜你喜欢

转载自blog.csdn.net/ansizhong9191/article/details/83410944
今日推荐