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

运行结果

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

相关推荐
chen(o561-6o623o7)14 分钟前
AI人工智能高架十字迷宫AI人工智能高架十字迷宫视频分析系统
经验分享
ulias21216 分钟前
单元最短路问题
数据库·c++·算法·动态规划
崎岖Qiu16 分钟前
leetcode380:RandomizedSet - O(1)时间插入删除和获取随机元素(数组+哈希表的巧妙结合)
java·数据结构·算法·leetcode·力扣·散列表
ZLRRLZ18 分钟前
【数据结构】图
数据结构·算法·图论
kida_yuan31 分钟前
【从零开始】13. 数据增强(Data Augmentation)
数据结构·python·nlp
Ada_疯丫头34 分钟前
杰伊·温格罗教我数据结构与算法
算法
小白开始进步39 分钟前
机器人集群调度算法简介与实现思路
算法·机器人
ajassi20001 小时前
开源 C++ QT Widget 开发(十六)程序发布
linux·c++·qt·开源
好易学·数据结构1 小时前
可视化图解算法60: 矩阵最长递增路径
数据结构·算法·leetcode·力扣·递归·回溯算法·牛客
SamsongSSS1 小时前
JavaScript逆向SM国密算法
javascript·算法·逆向