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

运行结果

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

相关推荐
py有趣14 分钟前
力扣热门100题之和为K的子数组
数据结构·算法·leetcode
hipolymers32 分钟前
C语言怎么样?难学吗?
c语言·数据结构·学习·算法·编程
CS创新实验室1 小时前
从“跑得动”到“跑得稳”:深度剖析数据结构究竟是理论点缀还是核心战力?
数据结构
jllllyuz2 小时前
MATLAB 蒙特卡洛排队等待模拟程序
数据结构·matlab
自我意识的多元宇宙2 小时前
树、森林——树、森林与二叉树的转换(森林转换为二叉树)
数据结构
xuhaoyu_cpp_java2 小时前
连接池学习
数据库·经验分享·笔记·学习
海清河晏1112 小时前
数据结构 | 双循环链表
数据结构·链表
workflower2 小时前
机器人应用-楼宇室内巡逻
大数据·人工智能·算法·microsoft·机器人·动态规划·享元模式
ZPC82102 小时前
fanuc 机器人通过PR寄存器实现轨迹控制
人工智能·算法·计算机视觉·机器人
py有趣2 小时前
力扣热门100题之编辑距离
数据结构·算法·leetcode