作者: 负雪明烛
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?

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

题目大意

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

解题方法

数组保存再随机选择

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

代码:

  1. # Definition for singly-linked list.
  2. # class ListNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution(object):
  7. def __init__(self, head):
  8. """
  9. @param head The linked list's head.
  10. Note that the head is guaranteed to be not null, so it contains at least one node.
  11. :type head: ListNode
  12. """
  13. self.stack = []
  14. while head:
  15. self.stack.append(head.val)
  16. head = head.next
  17. def getRandom(self):
  18. """
  19. Returns a random node's value.
  20. :rtype: int
  21. """
  22. _len = len(self.stack)
  23. return self.stack[random.randint(0, _len - 1)]
  24. # Your Solution object will be instantiated and called as such:
  25. # obj = Solution(head)
  26. # param_1 = obj.getRandom()

蓄水池抽样

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

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

算法的过程:

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

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

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

这个题中k = 1。

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. /** @param head The linked list's head.
  12. Note that the head is guaranteed to be not null, so it contains at least one node. */
  13. Solution(ListNode* head) : h_(head) {
  14. }
  15. /** Returns a random node's value. */
  16. int getRandom() {
  17. ListNode* head = h_;
  18. int cnt = 0, res = 0;
  19. while (head) {
  20. ++cnt;
  21. if (rand() % cnt == 0)
  22. res = head->val;
  23. head = head->next;
  24. }
  25. return res;
  26. }
  27. private:
  28. ListNode* h_;
  29. };
  30. /**
  31. * Your Solution object will be instantiated and called as such:
  32. * Solution obj = new Solution(head);
  33. * int param_1 = obj.getRandom();
  34. */

日期

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. (转载)SQL Server 2008 连接JDBC详细图文教程

    点评:SQL Server 2008是目前windows上使用最多的sql数据库,2008的安装机制是基于framework重写的,特点是非常耗时间SQL Server 2008是目前windows上 ...

  2. HDC2021技术分论坛:异构组网如何解决共享资源冲突?

    作者:lijie,HarmonyOS软总线领域专家 相信大家对HarmonyOS的"超级终端"比较熟悉了.那么,您知道超级终端场景下的多种设备在不同环境下是如何组成一个网络的吗?这 ...

  3. 以VuePress的v1.x为基础开发-用户手册

    首先配置.vuepress中的config.js module.exports = { title:"用户手册", description: '用户手册', evergreen: ...

  4. Express中间件原理详解

    前言 Express和Koa是目前最主流的基于node的web开发框架,他们的开发者是同一班人马.貌似现在Koa更加流行,但是仍然有大量的项目在使用Express,所以我想通过这篇文章说说Expres ...

  5. mybatis-plus条件构造用is开头的Boolean类型字段时遇到的问题

    is打头的Boolean字段导致的代码生成器与lambda构造器的冲突 https://gitee.com/baomidou/mybatis-plus/issues/I171DD?_from=gite ...

  6. html href页面跳转获取参数

    //传递参数 var id = columnData.id; var companyname = encodeURI(columnData.companyname); var linename = e ...

  7. RunLoop基础知识以及GCD

    - 1.1 字面意思   a 运行循环   b 跑圈   - 1.2 基本作用(作用重大)   a 保持程序的持续运行(ios程序因而能一直活着不会死)    b 处理app中的各种事件(比如触摸事件 ...

  8. 【Linux】【Services】【SaaS】Docker+kubernetes(10. 利用反向代理实现服务高可用)

    1. 简介 1.1. 由于K8S并没有自己的集群,所以需要借助其他软件来实现,公司的生产环境使用的是Nginx,想要支持TCP转发要额外安装模块,测试环境中我就使用HAPROXY了 1.2. 由于是做 ...

  9. Activiti工作流引擎使用详解(一)

    一.IDEA安装activiti插件 在插件库中查找actiBPM,安装该插件,如果找不到该插件,请到插件库中下载该包手动安装,插件地址 http://plugins.jetbrains.com/pl ...

  10. 如何使用gitHub管理自己的项目

    GitHub 与 Git Git是一种分布式版本控制系统,与svn是同样的概念 GitHub是一个网站,提供Git服务 前提:你的本机电脑已经安装了git,并且已经注册了gitHub账号 Git上传本 ...