作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/linked-list-random-node/description/

题目描述

Given a singly linked list, return a random node’s value from the linked list. Each node must have the same probability of being chosen.

Follow up:
What if the linked list is extremely large and its length is unknown to you? Could you solve this efficiently without using extra space?

Example:

// Init a singly linked list [1,2,3].
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
Solution solution = new Solution(head); // getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
solution.getRandom();

题目大意

随机从链表中抽出一个节点的数字。

解题方法

数组保存再随机选择

我使用一个数组保存了,然后从中间随机找的index。

代码:

# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None class Solution(object): def __init__(self, head):
"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
:type head: ListNode
"""
self.stack = []
while head:
self.stack.append(head.val)
head = head.next def getRandom(self):
"""
Returns a random node's value.
:rtype: int
"""
_len = len(self.stack)
return self.stack[random.randint(0, _len - 1)] # Your Solution object will be instantiated and called as such:
# obj = Solution(head)
# param_1 = obj.getRandom()

蓄水池抽样

这个做法和398. Random Pick Index完全一致,即在一个流中随机选择一个数字。

蓄水池采样算法(Reservoir Sampling)是说在一个流中,随机选择k个数字,保证每个数字被选择的概率相等。

算法的过程:

假设数据序列的规模为 n,需要采样的数量的为 k。

首先构建一个可容纳 k 个元素的数组,将序列的前 k 个元素放入数组中。

然后从第 k+1 个元素开始,以 k/n 的概率来决定该元素是否被替换到数组中(数组中的元素被替换的概率是相同的)。 当遍历完所有元素之后,数组中剩下的元素即为所需采取的样本。

这个题中k = 1。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
Solution(ListNode* head) : h_(head) {
} /** Returns a random node's value. */
int getRandom() {
ListNode* head = h_;
int cnt = 0, res = 0;
while (head) {
++cnt;
if (rand() % cnt == 0)
res = head->val;
head = head->next;
}
return res;
}
private:
ListNode* h_;
}; /**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(head);
* int param_1 = obj.getRandom();
*/

日期

2018 年 3 月 8 日
2019 年 2 月 26 日 —— 二月就要完了

【LeetCode】382. Linked List Random Node 解题报告(Python & C++)的更多相关文章

  1. [LeetCode] 382. Linked List Random Node 链表随机节点

    Given a singly linked list, return a random node's value from the linked list. Each node must have t ...

  2. Leetcode 382. Linked List Random Node

    本题可以用reservoir sampling来解决不明list长度的情况下平均概率选择元素的问题. 假设在[x_1,...,x_n]只选一个元素,要求每个元素被选中的概率都是1/n,但是n未知. 其 ...

  3. [LeetCode] 382. Linked List Random Node ☆☆☆

    Given a singly linked list, return a random node's value from the linked list. Each node must have t ...

  4. 382 Linked List Random Node 链表随机节点

    给定一个单链表,随机选择链表的一个节点,并返回相应的节点值.保证每个节点被选的概率一样.进阶:如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?示例:// 初始化一个单链表 ...

  5. 382. Linked List Random Node

    Given a singly linked list, return a random node's value from the linked list. Each node must have t ...

  6. 382. Linked List Random Node(蓄水池采样)

    1. 问题 给定一个单链表,随机返回一个结点,要求每个结点被选中的概率相等. 2. 思路 在一个给定长度的数组中等概率抽取一个数,可以简单用随机函数random.randint(0, n-1)得到索引 ...

  7. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  8. 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...

  9. 【LeetCode】743. Network Delay Time 解题报告(Python)

    [LeetCode]743. Network Delay Time 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

随机推荐

  1. ubuntu终端颜色快速配置

    ubuntu终端颜色快速配置 根据以下step步骤设置即可 step1:备份:cp ~/.bashrc ~/.bashrc.backup step2:打开文件:vim ~/.bashrc step3: ...

  2. Spark On Yarn的各种Bug

    今天将代码以Spark On Yarn Cluster的方式提交,遇到了很多很多问题.特地记录一下. 代码通过--master yarn-client提交是没有问题的,但是通过--master yar ...

  3. Learning Spark中文版--第四章--使用键值对(1)

      本章介绍了如何使用键值对RDD,Spark中很多操作都基于此数据类型.键值对RDD通常在聚合操作中使用,而且我们经常做一些初始的ETL(extract(提取),transform(转换)和load ...

  4. tableView和tableViewCell的背景颜色问题

    当在tableView中添加cell数据时,我们会发现原本设置的tableView的背景颜色不见了,这是因为加载cell数据时,tableView的背景颜色被cell数据遮盖住了,此时,可以通过设置c ...

  5. maven高级学习

    上一篇<maven是什么>介绍了最初级的maven学习,今天就趁着周末的大好时光一起学习下maven的高级知识吧. 1.maven工程要导入jar包的坐标,就必须要考虑解决jar冲突 1) ...

  6. 使用fastDFS上传和下载图片文件

    package com.xuecheng.test.fastdfs;import org.csource.common.MyException;import org.csource.fastdfs.* ...

  7. hooks中,useEffect无限调用问题产生的原因

    前言:我在我的另一篇博客中有说道useEffect监听对象或者数组时会导致useEffect无限执行,并给予了解决方案-useEffect无限调用问题 .后来我想从其产生根源去理解并解决这个问题. 原 ...

  8. HyperSnips:VSCode上的自动补全神器

    发现一个小众但是巨好用的VSCode自动补全插件:HyperSnips. 作者显然受到了 这位小哥 的启发,将 Vim Ultisnips 的大部分功能搬到了VSCode上.并用 JavaScript ...

  9. Python语法之变量

    一.变量简介 1.什么是变量 变量即变化的量,用于记录事物的某种状态,比如人的年龄.性别,游戏角色的等级.金钱. 2.如何使用变量 日常生活中: 姓名:Jason 年龄:18 爱好:音乐 程序中: u ...

  10. Markdown 语法粗学

    Markdown 语法粗学 Typora下载 Typora官网 下拉点击右上角 选择下载即可 里面选择自己想要的系统下载即可 如果下载缓慢,推荐使用各自的下载工具或者使用软件管家等 亲测迅雷速度尚可 ...