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;
    }
};
相关推荐
凌肖战1 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
GEEK零零七3 小时前
Leetcode 1103. 分糖果 II
数学·算法·leetcode·等差数列
重庆小透明5 小时前
力扣刷题记录【1】146.LRU缓存
java·后端·学习·算法·leetcode·缓存
desssq5 小时前
力扣:70. 爬楼梯
算法·leetcode·职场和发展
岁忧6 小时前
(LeetCode 面试经典 150 题 ) 58. 最后一个单词的长度 (字符串)
java·c++·算法·leetcode·面试·go
??tobenewyorker9 小时前
力扣打卡第二十一天 中后遍历+中前遍历 构造二叉树
数据结构·c++·算法·leetcode
凌肖战12 小时前
力扣网C语言编程题:快慢指针来解决 “寻找重复数”
c语言·算法·leetcode
Alfred king1 天前
面试150 生命游戏
leetcode·游戏·面试·数组
薰衣草23331 天前
一天两道力扣(1)
算法·leetcode·职场和发展
爱coding的橙子1 天前
每日算法刷题Day41 6.28:leetcode前缀和2道题,用时1h20min(要加快)
算法·leetcode·职场和发展