算法设计与分析课作业【week14】leetcode--45. Jump Game2

题目

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.

题目的要求是数组的每个位置上的数代表能从该位置移动的最大步数,每次从第一个位置开始,求跳到最后一个跟上次的jump game很像,但这次不求跳到是否可以跳最后一个位置,而是求跳到最后一个位置跳的最少次数。

这次我们依旧是贪心算法的思想,在每次能跳的最远距离之前,找到一个能跳的更远的位置,在找完之后我们便需要跳一次,然后重复跳,记录跳的次数,最终便得到了我们的结果。

以[2,1,3,1,2,1,5]为例,我们从下标为0开始跳,获得最远的的位置是2,在0-2之间,我们要找到下一次能跳到的最远距离,1下标能跳到2,2下标能跳到5,这样我们已经找完了0-2之间的能跳到的下一个最远距离的位置是5,现在我们离开2下标,便需要跳一次,然后我继续在3-5之间找下一个能跳到的最远的位置,3下标能跳到4,4下标能跳到6,这时我们已经跳到了数组最后一个位置了,所以我们可以停止了。当然我们也要记录下这次从3下标跳到最后一个位置的这一跳。这样我们就能解决问题了。

C++代码如下:

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值