题解 | #跳跃游戏(三)#

跳跃游戏(三)

https://www.nowcoder.com/practice/14abdfaf0ec4419cbc722decc709938b

贪心思想:时间复杂度O(N), 空间复杂度O(1)。

「C++ 代码」

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param nums int整型vector 
     * @return int整型
     */
    int minJumpStep(vector<int>& nums) {
        int n = nums.size();
        // 数组长度为0时无法跳跃,返回-1
        if(n==0)    return -1;
        int step = 0;
        // end记录的是下一个跳跃位置
        int end = 0;
        // further记录的是下下一个跳跃位置
        int further = 0;
        for(int i=0; i<n-1; ++i){
            further = max(further, nums[i] + i);
            if(i == end){
                if(i == further) return -1;
                ++step;
                end = further;
            }
        }
        return further >= (n-1) ? step : -1;
    }
};

全部评论

相关推荐

03-31 17:40
已编辑
门头沟学院 算法工程师
程序员牛肉:小牛肉来也! 也不要焦虑啦,你第一志愿还没有结束,只是回到人才库(泡大池子等待各个部门挑选)而已。仅仅代表你不符合这个组的用人标准,并不能够说明你在本次暑期实习中没机会加入美团了。 还是平复好心态,不断的复盘,等待下一次面试就好了。
点赞 评论 收藏
分享
评论
3
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务