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();
 */

运行结果

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

相关推荐
智者知已应修善业6 分钟前
【51单片机:两边向中间流水:即两边先点亮然后熄灭,次边的点亮再熄灭,直到最中间的两个点亮再熄灭,然后重复动作。】2023-3-4
c语言·c++·经验分享·笔记·嵌入式硬件·算法·51单片机
醒过来摸鱼38 分钟前
9.11 傅里叶变换家族介绍
线性代数·算法·概率论
是苏浙1 小时前
2025年11月17日力扣刷题小记
算法·刷题
@卞1 小时前
ST 表相关练习题
数据结构·c++·算法
醒过来摸鱼1 小时前
9.8 贝塞尔曲线
线性代数·算法·numpy
报错小能手1 小时前
C++笔记 bind函数模板
开发语言·c++·笔记
Vanranrr1 小时前
表驱动编程实战:让 UI 逻辑既清晰又好维护
c++·ui
Vanranrr1 小时前
车机项目中的 Widget 设计反思:从“能用”到“好用”的改进方向
c语言·c++·架构
2501_941111522 小时前
C++中的适配器模式
开发语言·c++·算法
2501_941111942 小时前
C++中的适配器模式变体
开发语言·c++·算法