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;
    }
};
相关推荐
IronMurphy7 分钟前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209258 分钟前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
承渊政道2 小时前
【优选算法】(实战体会位运算的逻辑思维)
数据结构·c++·笔记·学习·算法·leetcode·visual studio
Frostnova丶2 小时前
LeetCode 2573. 找出对应 LCP 矩阵的字符串
算法·leetcode·矩阵
承渊政道3 小时前
【优选算法】(实战推演模拟算法的蕴含深意)
数据结构·c++·笔记·学习·算法·leetcode·排序算法
篮l球场6 小时前
数组中的第K个最大元素
数据结构·算法·leetcode
篮l球场7 小时前
前 K 个高频元素
数据结构·算法·leetcode
_深海凉_10 小时前
LeetCode热题100-两数之和
算法·leetcode·职场和发展
阿Y加油吧11 小时前
面试硬核双杀!合并 K 个升序链表 + LRU 缓存|力扣高频手撕原题全解
数据结构·leetcode·链表
老鼠只爱大米11 小时前
LeetCode经典算法面试题 #70:爬楼梯(朴素递归、记忆化递归、动态规划等六种实现方案详解)
算法·leetcode·动态规划·递归·斐波那契·矩阵快速幂·爬楼梯