【leetcode】【hard】【每日一题】45. Jump Game II​​​​​​​

230 篇文章 0 订阅

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.

题目链接:https://leetcode-cn.com/problems/jump-game-ii/

 

思路

原本思路是BFS,把每个位置能到达的新位置方案加入队列中,同时每个新位置只考虑一次,复杂度O(n)。

但这个方法在大数据下超时了。

class Solution {
public:
    int jump(vector<int>& nums) {
        int len = nums.size();
        if(len<=1) return 0;
        vector<bool> rec(len, false);
        int res = 0, cur = 0;
        rec[0] = true;
        queue<int> q;
        q.push(cur);
        while(!q.empty()){
            ++res;
            int n = q.size();
            for(int k=0; k<n; ++k){
                cur = q.front();
                q.pop();
                int tmp = nums[cur];
                for(int i=1; i<=tmp; ++i){
                    if(cur+i == len-1){
                        return res;
                    }else if(cur+i<len-1 && !rec[cur+i]){
                        q.push(cur+i);
                        rec[cur+1] = true;
                    }
                }
            }
        }
        return res;
    }
};

后来看了解析,使用了贪心的思想,复杂度也同样是O(n),但是判断和状态存储少。

核心思路是每一步计算其能到达的最远地方,在计算最远的时候也是将每个可能位置逐个判断,也可以说是一种BFS的思维,但实现上比我的方法精简得不少。

maxPos用于记录当前能去到的最远位置,end用于记录所走步数增加的分界位置。

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值