Leetcode—382. 链表随机节点【中等】(水塘抽样法)

2024每日刷题(一零九)

Leetcode---382. 链表随机节点

算法思想

我们可以在初始化时,用一个数组记录链表中的所有元素,这样随机选择链表的一个节点,就变成在数组中随机选择一个元素

实现代码

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    vector<int> arr;
    Solution(ListNode* head) {
        for(ListNode* cur = head; cur; cur=cur->next) {
            arr.push_back(cur->val);
        }
    }
    
    int getRandom() {
        return arr[rand()%arr.size()];
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */

运行结果

水塘抽样法

实现代码

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    Solution(ListNode* head): sohead(head) {

    }
    
    int getRandom() {
        int ans = 1e5;
        int i = 1;
        for(ListNode* cur = sohead; cur; cur = cur->next, i++) {
            if(rand()%i==0) {
                ans = cur->val;
            }
        }
        return ans;
    }
private:
    ListNode* sohead;
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */

运行结果

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

相关推荐
天天爱吃肉82184 小时前
【跨界封神|周杰伦×王传福(陶晶莹主持):音乐创作与新能源NVH测试,底层逻辑竟完全同源!(新人必看入行指南)】
python·嵌入式硬件·算法·汽车
im_AMBER4 小时前
Leetcode 114 链表中的下一个更大节点 | 删除排序链表中的重复元素 II
算法·leetcode
EmbedLinX4 小时前
嵌入式之协议解析
linux·网络·c++·笔记·学习
xhbaitxl4 小时前
算法学习day38-动态规划
学习·算法·动态规划
多恩Stone4 小时前
【3D AICG 系列-6】OmniPart 训练流程梳理
人工智能·pytorch·算法·3d·aigc
wangjialelele4 小时前
Linux中的进程管理
java·linux·服务器·c语言·c++·个人开发
历程里程碑4 小时前
普通数组----轮转数组
java·数据结构·c++·算法·spring·leetcode·eclipse
pp起床4 小时前
贪心算法 | part02
算法·leetcode·贪心算法
sin_hielo4 小时前
leetcode 1653
数据结构·算法·leetcode
2501_901147834 小时前
面试必看:优势洗牌
笔记·学习·算法·面试·职场和发展