题目

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

思路

最近的题目感觉和随机数相关的比较多,不过这个确实是面试的趋势。对于本题目,我们首先看看允许使用额外空间的解法,然后再看看如果不允许使用额外空间,怎么利用Reservior Sampling方法获得随机结点,这应该是本题目考查的重点。

1、使用额外空间:我们将单链表的结点值都拷贝到一个数组中,然后产生一个随机数索引,返回随机索引对应的值即可。这种做法的空间复杂度是O(n);构造函数的时间复杂度是O(n),getRandom函数的时间复杂度是O(1)。另外一个变种是我们在构造函数中计算出整个单链表的长度length,然后在getRandom方法中,随机产生一个介于[0, length]之间的数x,然后遍历单链表,返回第x个结点。这种做法的空间复杂度可以降低到O(1),但是getRandom的时间复杂度是O(n)。以上两种做法在length变为无限大的时候都会失效。

2、不使用额外空间:先来介绍一下Reservior Sampling方法,这种采样非常适合于流数据。怎么做呢?假设目前我们已经处理了n个结点,而当前选中的采样点是x(1 <= x <= n);这样当我们遇到第n+1个结点的时候,让x以1 / (n + 1)的概率转移到第n+1个结点。可以用概率论的知识证明当处理完所有结点后,每个结点被采样的概率是相同的。具体实现请见下面的代码。

代码

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) {ListNode* node = head;while(node != NULL) {vec.push_back(node->val);node = node->next;}}/** Returns a random node's value. */int getRandom() {if(vec.size() == 0) {return -1;}return vec[rand() % vec.size()];}
private:vector<int> vec;
};/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(head);* int param_1 = obj.getRandom();*/

2、不使用额外空间:

/*** 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) {random_list = head;}/** Returns a random node's value. */int getRandom() {ListNode* temp = random_list;int value = random_list->val;for (int i = 1; temp != NULL; ++i) {if (rand() % i == 0) {      // the propability is 1 / ivalue = temp->val;}temp = temp->next;}return value;}
private:ListNode* random_list;
};/*** Your Solution object will be instantiated and called as such:* Solution obj = new Solution(head);* int param_1 = obj.getRandom();*/

[Leetcode] 382. Linked List Random Node 解题报告相关推荐

  1. leetcode 382. Linked List Random Node | 382. 链表随机节点(Java)

    题目 https://leetcode.com/problems/linked-list-random-node/ 题解 先存起来,再随机返回即可.不知道在考察什么? /*** Definition ...

  2. LeetCode第45场双周赛-解题报告

    LeetCode第45场双周赛-解题报告 A. 唯一元素的和 原题链接 https://leetcode-cn.com/problems/sum-of-unique-elements/ 解题思路 因为 ...

  3. 【LeetCode】436. Find Right Interval 解题报告(Python)

    [LeetCode]436. Find Right Interval 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: h ...

  4. [Swift]LeetCode382. 链表随机节点 | Linked List Random Node

    原文地址:https://www.cnblogs.com/strengthen/p/10282841.html Given a singly linked list, return a random ...

  5. LeetCode Linked List Random Node(蓄水池采样算法)

    问题:给出一个单链表,随机选择链表中的一个节点,返回相应的值.保证每个节点被选的概率一样 思路:每次只保留一个数,当遇到第 i 个数时,以 1/i的概率保留它,(i-1)/i的概率保留原来的数. 具体 ...

  6. leetcode 214. 最短回文串 解题报告

    给定一个字符串 s,你可以通过在字符串前面添加字符将其转换为回文串.找到并返回可以用这种方式转换的最短回文串. 示例 1: 输入: "aacecaaa" 输出: "aaa ...

  7. [leetcode] 273. Integer to English Words 解题报告

    题目链接:https://leetcode.com/problems/integer-to-english-words/ Convert a non-negative integer to its e ...

  8. LeetCode: Median of Two Sorted Arrays 解题报告

    Median of Two Sorted Arrays There are two sorted arrays A and B of size m and n respectively. Find t ...

  9. 【LeetCode】House Robber I II 解题报告

    [题目] I You are a professional robber planning to rob houses along a street. Each house has a certain ...

  10. [Leetcode] 74. Search a 2D Matrix 解题报告

    题目: Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the f ...

最新文章

  1. 贝尔实验室发布6G通信白皮书
  2. 使用CoreData的轻量级自动数据迁移
  3. 006-SDK框架之LYWSDKInterfaceProtocol.h
  4. 用python实现矩阵乘法
  5. oracle修改参数
  6. java参数传入的是一个类名_Java编程细节——泛型的定义(类、接口、对象)、使用、继承...
  7. javascript犀牛书_犀牛书作者:最该忘记的JavaScript特性
  8. Java并发编程实战~StampedLock
  9. 十年云计算大爆发,微软正在摧毁其它竞争对手
  10. Kubernetes-NodePort(十七)
  11. Java 面向对象 --单例模式
  12. 安卓linux输入代码在哪里,输入  |  Android 开源项目  |  Android Open Source Project
  13. 三星active2怎么连接手机_手机怎么连接隐藏的wifi无线网络
  14. 什么是大数据分析平台
  15. perl python json_JSON Perl
  16. 一行Python代码玩转emoji表情,已经玩坏了都...
  17. 计算机考研浙江理工和江苏大学,杭州电子科技大和浙江理工大学这两所大学怎么样?哪所好?...
  18. Matlab-SEIR传染病模型预测
  19. ogc是一个非营利性组织_如果高科技公司变成非营利组织怎么办?
  20. AUI素材网-网站模板源码下载

热门文章

  1. 小女子做销售 四大温柔手段
  2. 没有比粥更温柔的了。念予毕生流离红尘,就找不到一个似粥温柔的人。
  3. 40行代码的Python爬虫案例:虎牙-王者荣耀主播的人气排行
  4. INS/GNSS组合导航(一)全球导航卫星系统对比
  5. 常见距离算法-欧氏距离、杰卡德距离、余弦距离
  6. 使用软碟通做启动盘给电脑装系统时如何分区
  7. 征战光伏沙场 第三方如何“护航”电站?
  8. 好看的皮囊 · 也是大自然的杰作 · 全球高质量 · 美图 · 集中营 · 美女 · 2017-08-24期...
  9. 关于微信适配的坑==》ios、安卓强制微信字体
  10. 【python】用递归解决汉洛塔问题