【LeetCode】45.跳跃游戏II

题目链接:

45.跳跃游戏

题目描述:

思路一(广度优先搜索算法BFS)

通过广度优先搜索算法寻找最短距离

代码实现:

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int n = nums.size();
        if(n<=1) return 0;

        vector<int> visited(n,0);
        queue<pair<int, int>> qu;
        qu.push({0,0});
        visited[0] = 1;
        int ans = 0;

        while(!qu.empty()){
            pair<int, int> cur = qu.front();
            qu.pop();
            int index = cur.first;
            int step = cur.second;

            for(int k = nums[index]; k>0; k--){
                // 跳跃k步
                if((k+index) >= n-1){
                    ans = step+1;
                    break;
                }else{
                    if(visited[k+index] != 1){
                        qu.push({k+index, step+1});
                        visited[k+index] = 1;
                    }
                }
            }
            if(ans!=0){
                break;
            }
        }

        return ans;
    }
};

思路二(贪心算法)

例如,对于数组 [ 2 , 3 , 1 , 2 , 4 , 2 , 3 ] [2,3,1,2,4,2,3] [2,3,1,2,4,2,3], 初始位置是下标 0,从下标 0 出发,最远可到达下标 2。下标 0 可到达的位置中,下标 1 的值是 3,从下标 1 出发可以达到更远的位置,因此第一步到达下标 1。从下标 1 出发,最远可到达下标 4。下标 1 可到达的位置中,下标 4 的值是 4 ,从下标 4 出发可以达到更远的位置,因此第二步到达下标 4。

代码实现:

cpp 复制代码
class Solution {
public:
    int jump(vector<int>& nums) {
        int maxPos = 0;
        int n = nums.size();
        int end = 0;
        int 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;
    }
};
相关推荐
郝学胜-神的一滴1 小时前
Leetcode 969 煎饼排序✨:翻转间的数组排序艺术
数据结构·c++·算法·leetcode·面试
炸膛坦客8 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
I_LPL8 小时前
hot100贪心专题
数据结构·算法·leetcode·贪心
颜酱9 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
WolfGang0073219 小时前
代码随想录算法训练营 Day16 | 二叉树 part06
算法
炸膛坦客9 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_8318249610 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~10 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you11 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_4160187211 小时前
C++中的状态模式
开发语言·c++·算法