LEETCODE 45. Jump Game II

LEETCODE 45. Jump Game II

题目大意

给出一个正整数数组,每个元素代表当前位置所能跳转的最大步数,求能到达数组最后的的最少跳转次数,实际上是44题的一个变种,44题只是判断能否到达数组最后,本题多加一个要记录最少跳转次数的要求。
例如
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.)

解题思路

也是贪心策略,记录所能到达最大下标,并且在更新最大下标的时候更新最小步数,当最大下标大于等于数组最后的时候,直接返回这个最小步数

实现代码

超时

class Solution {
public:
    int jump(vector<int>& nums) {
        const int arraySize = int(nums.size());
        int timesArray[arraySize];
        int rightBound = 1, leftBound = 0;
        for (int i = 1; i < arraySize; i++) {
            timesArray[i] = INT_MAX;
        }
        timesArray[0] = 0;
        while (leftBound < arraySize) {
            int newRightBound = rightBound;
            for (int i = leftBound; i < rightBound && i < arraySize; i++) {
                for (int j = 1; j <= nums[i]; j++) {
                    if (i + j + 1 > newRightBound) {
                        newRightBound = i + j + 1;
                    }
                    if (i + j < arraySize && timesArray[i] + 1 < timesArray[i + j]) {
                        timesArray[i + j] = timesArray[i] + 1;
                    }
                    if (i + j >= arraySize && timesArray[i] + 1 < timesArray[arraySize - 1]) {
                        timesArray[arraySize - 1] = timesArray[i] + 1;
                    }
                }
            }
            if (rightBound == newRightBound) {
                return newRightBound >= arraySize - 1?timesArray[arraySize - 1]:0;
            }
            leftBound = rightBound;
            rightBound = newRightBound;
        }
        return timesArray[arraySize - 1];
    }
};

改善

class Solution {
public:
    int jump(vector<int>& nums) {
        int index = 0, rightBound = 0, maxInd = nums[0], minStep = 1;
        while (index < nums.size() - 1 && index <= rightBound) {
            for (int i = index; i <= rightBound; i++) {
                maxInd = max(maxInd, i + nums[i]);
            }
            index = rightBound + 1;
            if (maxInd > rightBound) {
                if (maxInd >= nums.size() - 1) {
                    return minStep;
                }
                minStep++;
                rightBound = maxInd;
            } else {
                break;
            }
        }
        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值