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 分钟前
LeetCode 刷题【126. 单词接龙 II】
算法·leetcode·职场和发展
aloha_78930 分钟前
力扣hot100做题整理91-100
数据结构·算法·leetcode
Tiny番茄35 分钟前
31.下一个排列
数据结构·python·算法·leetcode
挂科是不可能出现的35 分钟前
最长连续序列
数据结构·c++·算法
_Aaron___1 小时前
List.subList() 返回值为什么不能强转成 ArrayList
数据结构·windows·list
前端小L1 小时前
动态规划的“数学之魂”:从DP推演到质因数分解——巧解「只有两个键的键盘」
算法·动态规划
我要学习别拦我~2 小时前
雷达图有什么优点与致命缺陷:一把“双刃剑”的可视化武器
经验分享·信息可视化
RTC老炮2 小时前
webrtc弱网-ReceiveSideCongestionController类源码分析及算法原理
网络·算法·webrtc
mjhcsp2 小时前
C++ int 类型深度解析:从底层实现到实战应用
c++·int
21号 12 小时前
9.Redis 集群(重在理解)
数据库·redis·算法