前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【蓄水池抽样】多语言入门「蓄水池抽样」知识点

【蓄水池抽样】多语言入门「蓄水池抽样」知识点

作者头像
宫水三叶的刷题日记
发布2022-05-27 14:07:52
2840
发布2022-05-27 14:07:52
举报

题目描述

这是 LeetCode 上的「382. 链表随机节点」,难度为「中等」

Tag :「链表」、「模拟」、「蓄水池抽样」

给你一个单链表,随机选择链表的一个节点,并返回相应的节点值。每个节点 被选中的概率一样

实现 Solution 类:

  • Solution(ListNode head) 使用整数数组初始化对象。
  • int getRandom() 从链表中随机选择一个节点并返回该节点的值。链表中所有节点被选中的概率相等。

示例:

代码语言:javascript
复制
输入
["Solution", "getRandom", "getRandom", "getRandom", "getRandom", "getRandom"]
[[[1, 2, 3]], [], [], [], [], []]

输出
[null, 1, 3, 2, 2, 3]

解释
Solution solution = new Solution([1, 2, 3]);
solution.getRandom(); // 返回 1
solution.getRandom(); // 返回 3
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 2
solution.getRandom(); // 返回 3
// getRandom() 方法应随机返回 1、2、3中的一个,每个元素被返回的概率相等。

模拟

在查询时随机一个下标,并将数组中对应下标内容返回出去。

Java 代码:

代码语言:javascript
复制
class Solution {
    List<Integer> list = new ArrayList<>();
    Random random = new Random(20220116);
    public Solution(ListNode head) {
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
    }
    public int getRandom() {
        int idx = random.nextInt(list.size());
        return list.get(idx);
    }
}

Python(感谢 Benhao总 提供的其他语言版本):

代码语言:javascript
复制
class Solution:

    def __init__(self, head: Optional[ListNode]):
        self.nodes = []
        while head:
            self.nodes.append(head)
            head = head.next

    def getRandom(self) -> int:
        return self.nodes[randint(0, len(self.nodes) - 1)].val

C++(感谢 可乐总 提供的其他语言版本):

代码语言:javascript
复制
class Solution {
public:
    vector<int> list;
    Solution(ListNode* head) {
        while(head){
            list.push_back(head->val);
            head = head->next;
        }
    }
    int getRandom() {
        return list[rand() % list.size()];
    }
};

蓄水池抽样

Java 代码:

代码语言:javascript
复制
class Solution {
    ListNode head;
    Random random = new Random(20220116);
    public Solution(ListNode _head) {
        head = _head;
    }
    public int getRandom() {
        int ans = 0, idx = 0;
        ListNode t = head;
        while (t != null && ++idx >= 0) {
            if (random.nextInt(idx) == 0) ans = t.val;
            t = t.next;
        }
        return ans;
    }
}

Python(感谢 Benhao总 提供的其他语言版本):

代码语言:javascript
复制
class Solution:

    def __init__(self, head: Optional[ListNode]):
        self.root = head

    def getRandom(self) -> int:
        node, ans, i = self.root, None, 0
        while node:
            if not randint(0, i):
                ans = node.val
            node, i = node.next, i + 1
        return ans

C++(感谢 可乐总 提供的其他语言版本):

代码语言:javascript
复制
class Solution {
public:
    ListNode* head;
    Solution(ListNode* _head) {
        head = _head;
    }
    int getRandom() {
        int ans = 0, idx = 0;
        auto t = head;
        while(t != NULL){
            idx++;
            if(rand() % idx == 0) ans = t->val;
            t = t->next;
        }
        return ans;
    }
};

最后

这是我们「刷穿 LeetCode」系列文章的第 No.382 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2022-04-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 宫水三叶的刷题日记 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 模拟
  • 最后
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档