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

解法:

  由于无法确定链表的长度,或者链表的长度很长,因此需要采用水塘抽样算法。由于限定了head一定存在,所以我们先让返回值res等于head的节点值,然后让curr指向head的下一个节点,定义一个变量count,初始化为1,若curr不为空我们开始循环,我们在[0, count)中取一个随机数,如果取出来0,那么我们更新res为当前的curr的节点值,然后此时count自增一,curr指向其下一个位置,这里其实相当于我们维护了一个大小为1的水塘,然后我们随机数生成为0的话,我们交换水塘中的值和当前遍历到底值,这样可以保证每个数字的概率相等,参见代码如下:

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution { private ListNode 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. */
public Solution(ListNode head) {
this.head = head;
} /** Returns a random node's value. */
public int getRandom() {
int count = 1;
int res = head.val;
ListNode curr = head.next;
while (curr != null) {
if (new Random().nextInt(++count) == 0) {
res = curr.val;
}
curr = curr.next;
}
return res;
}
} /**
* 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 链表随机节点

    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 解题报告(Python & C++)

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

  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] 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. LeetCode: Linked List Random Node

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

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

随机推荐

  1. 《Spring2之站立会议4》

    <Spring2之站立会议4> 昨天,对主界面进行了设计,编写了主界面的代码,把文本输入框,显示框,发送,关闭两个按钮的功能实现了: 今天,接着对主界面进行代码的编写,实现了界面的美化,从 ...

  2. 2016011998+sw

    Coding.net原码仓库地址:https://git.coding.net/laolaf/sw.git 目录 1 需求分析 2 功能设计 3 设计实现 4 算法详解 5 测试运行 6 满意代码 1 ...

  3. TCP/IP Illustrated Vol1 Second Edition即英文版第二版,TCP部分个人勘误

    目前已经有了英文版第二版的TCPIP详解,中文版暂时还没有,但是英文版还是有好几处错误,作者和官方竟然没有维护一个勘误表. 个人阅读过程中针对TCP部分可能有问题的地方简单勘误一下 P596:示意图中 ...

  4. 转载---Atom编辑器常用快捷键

    常用快捷键–亲测及翻译 英文 中文 快捷键 功能 New Window 新建界面窗口 Ctrl + Shift + N 如中文意思 New File 新建文件 Ctrl + N 如中文意思 Open ...

  5. Sprint1回顾

    Sprint目标 此产品为适用于小学生使用的四则运算训练软件.关于第一期Sprint冲刺的目标,我们打算实现产品的以下几点的功能: •1.初始界面设计 •2.四则基本运算算法 •3.能产生随机式子 • ...

  6. HTML与URL两种录制模式分析(转)

    如何选择两种模式? 1.基于浏览器的应用程序推荐使用HTML-Based Script. 2.不是基于浏览器的应用程序推荐使用URL-Based Script. 3.如果基于浏览器的应用程序中包含了J ...

  7. 每秒更新时间 v-text的应用 (解决闪现{}问题)

    有闪现<div id="app"> {{date}}</div> 无闪现<div id="app" v-text:date=&qu ...

  8. Read N Characters Given Read4 II - Call multiple times

    The API: int read4(char *buf) reads 4 characters at a time from a file. The return value is the actu ...

  9. 相见恨晚的 scala - 01 [ 基础 ]

    简洁到不行,多一个分号都是不应该. 学习笔记: centOS 下安装 scala 和安装 jdk 一毛一样 . 1 . 不同于 Java 的变量声明 :( 但是和 js 很像 ) /** * Crea ...

  10. SpringMVC 之 mvc:exclude-mapping 不拦截某个请求

    在使用 SpringMVC 是,配置了一个 Session 拦截器,用于拦截用户是否登录,但是用户访问登录页面和注册页面时就不需要拦截了,这时就需要用到这个标签了 <mvc:execlude-m ...