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

这道题给了我们一个链表,让随机返回一个节点,那么最直接的方法就是先统计出链表的长度,然后根据长度随机生成一个位置,然后从开头遍历到这个位置即可,参见代码如下:

解法一:

class Solution {
public:
Solution(ListNode* head) {
len = ;
ListNode *cur = head;
this->head = head;
while (cur) {
++len;
cur = cur->next;
}
}
int getRandom() {
int t = rand() % len;
ListNode *cur = head;
while (t) {
--t;
cur = cur->next;
}
return cur->val;
}
private:
int len;
ListNode *head;
};

Follow up 中说链表可能很长,我们没法提前知道长度,这里用到了著名了 水塘抽样 Reservoir Sampling 的思路,由于限定了 head 一定存在,所以先让返回值 res 等于 head 的节点值,然后让 cur 指向 head 的下一个节点,定义一个变量i,初始化为2,若 cur 不为空则开始循环,在 [0, i - 1] 中取一个随机数,如果取出来0,则更新 res 为当前的 cur 的节点值,然后此时i自增一,cur 指向其下一个位置,这里其实相当于维护了一个大小为1的水塘,然后随机数生成为0的话,交换水塘中的值和当前遍历到的值,这样可以保证每个数字的概率相等,参见代码如下:

解法二:

class Solution {
public:
Solution(ListNode* head) {
this->head = head;
}
int getRandom() {
int res = head->val, i = ;
ListNode *cur = head->next;
while (cur) {
int j = rand() % i;
if (j == ) res = cur->val;
++i;
cur = cur->next;
}
return res;
}
private:
ListNode *head;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/382

类似题目:

Random Pick Index

参考资料:

https://leetcode.com/problems/linked-list-random-node/

https://leetcode.com/problems/linked-list-random-node/discuss/85662/Java-Solution-with-cases-explain

https://leetcode.com/problems/linked-list-random-node/discuss/85659/Brief-explanation-for-Reservoir-Sampling

https://leetcode.com/problems/linked-list-random-node/discuss/85701/O(n)-Time-and-O(1)-Space-Java-Solution

https://leetcode.com/problems/linked-list-random-node/discuss/85690/using-reservoir-sampling-o1-space-on-time-complexityuff0cc

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Linked List Random Node 链表随机节点的更多相关文章

  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. 382 Linked List Random Node 链表随机节点

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

  3. LeetCode: Linked List Random Node

    这题参照http://blog.jobbole.com/42550/ 用的蓄水池算法,即更改ans的概率为1/(当前length) /** * Definition for singly-linked ...

  4. Java实现 LeetCode 382 链表随机节点

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

  5. [Swift]LeetCode382. 链表随机节点 | 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. 【LeetCode】382. Linked List Random Node 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 数组保存再随机选择 蓄水池抽样 日期 题目地址:ht ...

  7. [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 ...

  8. Linked List Random Node -- LeetCode

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

  9. Leetcode 382. Linked List Random Node

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

随机推荐

  1. Bootstrap框架的学习(二)

    一.下载Bootstrap Bootstrap (当前版本 v3.3.0)提供以下几种方式帮你快速上手,每一种方式针对具有不同技能等级的开发者和不同的使用场景. 下载地址:http://v3.boot ...

  2. C#组件系列———又一款日志组件:Elmah的学习和分享

    前言:好久没动笔了,都有点生疏,12月都要接近尾声,可是这月连一篇的产出都没有,不能坏了“规矩”,今天还是来写一篇.最近个把月确实很忙,不过每天早上还是会抽空来园子里逛逛.一如既往,园子里每年这个时候 ...

  3. ASP.NET Core 中文文档 第二章 指南(4.5)使用 SQL Server LocalDB

    原文:Working with SQL Server LocalDB 作者:Rick Anderson 翻译: 魏美娟(初见) 校对: 孟帅洋(书缘).张硕(Apple).许登洋(Seay) Appl ...

  4. react-native学习笔记--史上最详细Windows版本搭建安装React Native环境配置

    参考:http://www.lcode.org/react-native/ React native中文网:http://reactnative.cn/docs/0.23/android-setup. ...

  5. 通过向页面写html代码导出excel

    //excel文件名 string filename = "考勤汇总"; StringBuilder ExcelHtml = new StringBuilder(); ExcelH ...

  6. 成就PHP高手的五个必由之路

    亲们,此文时转载过来的,不是原创!特此说明一下 原文名称:5 ways to be a better php developer原文链接:http://www.developertutorials.c ...

  7. 设置JDK环境变量(linux版)

     设置环境变量一.修改/etc/profile文件当本机仅仅作为开发使用时推荐使用这种方法,因为此种配置时所有用户的shell都有权使用这些环境变量,可能会给系统带来安全性问题.用文本编辑器打开/et ...

  8. jQuery的$.ajax

    在介绍JSONP之前,先简单的介绍一些JSON.JSON是JavaScript Object Notation的缩写,是一种轻量的.可读的基于文本的数据交换开放标准.源于JavsScript编程语言中 ...

  9. 【问题】Asp.net MVC 的cshtml页面中调用JS方法传递字符串变量参数

    [问题]Asp.net MVC 的cshtml页面中调用JS方法传递字符串变量参数. [解决]直接对变量加引号,如: <button onclick="deleteProduct('@ ...

  10. freemarker页面中文乱码

    一.前言 简单的记录freemarker遇到的错误问题:ftl页面中文乱码 由于freemarker整合在ssm框架中,所以笔者直接贴配置代码 <beans xmlns="http:/ ...