leetcode 1345. 跳跃游戏 IV

题目:1345. 跳跃游戏 IV - 力扣(LeetCode)

经典bfs,关键是建立所有"arr[i] == arr[j]"的连接。我的做法是用额外的存储,记录每个整数的前后整数都是哪个,再对数组排序。每个整数搜索的下个节点就是prev、next和数组中相邻且相等的整数:

cpp 复制代码
struct Node {
    int val;
    int index;
    int jumps = -1;
    Node* prev = nullptr;
    Node* next = nullptr;
    Node(int val) {
        this->val = val;
    }
};
bool myComp(Node* a, Node* b) {
    return a->val < b->val;
}
class Solution {
public:
    int minJumps(vector<int>& arr) {
        size_t n = arr.size();
        if (n <= 1) {
            return 0;
        }
        vector<Node*> nodes(n);
        for (int i = 0; i < n; i++) {
            nodes[i] = new Node(arr[i]);
            if (i > 0) {
                nodes[i - 1]->next = nodes[i];
                nodes[i]->prev = nodes[i - 1];
            }
        }
        list<Node*> bfs;
        bfs.push_back(nodes[0]);
        nodes[0]->jumps = 0;
        Node* tail = nodes[n - 1];
        sort(nodes.begin(), nodes.end(), myComp);
        for (int i = 0; i < n; i++) {
            nodes[i]->index = i;
        }
        
        Node* t;
        int i;
        while (!bfs.empty()) {
            t = bfs.front();
            bfs.pop_front();
            i = t->index - 1;
            while (i >= 0 && nodes[i]->val == t->val && nodes[i]->jumps == -1) {
                nodes[i]->jumps = t->jumps + 1;
                bfs.push_back(nodes[i]);
                i--;
            }
            i = t->index + 1;
            while (i < n && nodes[i]->val == t->val && nodes[i]->jumps == -1) {
                nodes[i]->jumps = t->jumps + 1;
                bfs.push_back(nodes[i]);
                i++;
            }
            if (t->prev && t->prev->jumps == -1) {
                t->prev->jumps = t->jumps + 1;
                bfs.push_back(t->prev);
            }
            if (t->next && t->next->jumps == -1) {
                t->next->jumps = t->jumps + 1;
                bfs.push_back(t->next);
            }
            if (tail->jumps != -1) {
                return tail->jumps;
            }
        }
        return (int) n - 1;
    }
};
相关推荐
薰衣草23333 小时前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子4 小时前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展
前端拿破轮6 小时前
不是吧不是吧,leetcode第一题我就做不出来?😭😭😭
后端·算法·leetcode
前端拿破轮6 小时前
😭😭😭看到这个快乐数10s,我就知道快乐不属于我了🤪
算法·leetcode·typescript
今天背单词了吗98012 小时前
算法学习笔记:4.KMP 算法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·考研·算法·leetcode·kmp算法
hn小菜鸡18 小时前
LeetCode 377.组合总和IV
数据结构·算法·leetcode
亮亮爱刷题10 天前
飞往大厂梦之算法提升-7
数据结构·算法·leetcode·动态规划
zmuy10 天前
124. 二叉树中的最大路径和
数据结构·算法·leetcode
chao_78910 天前
滑动窗口题解——找到字符串中所有字母异位词【LeetCode】
数据结构·算法·leetcode
Alfred king10 天前
面试150跳跃游戏
python·leetcode·游戏·贪心算法