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 effi…
本题可以用reservoir sampling来解决不明list长度的情况下平均概率选择元素的问题. 假设在[x_1,...,x_n]只选一个元素,要求每个元素被选中的概率都是1/n,但是n未知. 其中 random.randint(0, cnt) == 0: 的概率是1/(cnt+1).reservoir sampling的证明可以使用归纳法(induction). class Solution(object): def __init__(self, head): """…
作者: 负雪明烛 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. E…
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 effic…
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 effi…
1. 问题 给定一个单链表,随机返回一个结点,要求每个结点被选中的概率相等. 2. 思路 在一个给定长度的数组中等概率抽取一个数,可以简单用随机函数random.randint(0, n-1)得到索引来抽取. 本题是给定了链表,当然也好做,可以事先遍历一次求长度,每次要取的时候随机求索引,然后遍历一次. 时间复杂度O(n),空间复杂度O(1) 或者事先把数据放到数组中,每次要取的时候随机求索引,然后直接取到对应的数. 时间复杂度O(1),空间复杂度O(n) (延伸一下)如果对于长度未知,会不断增…
给定一个单链表,随机选择链表的一个节点,并返回相应的节点值.保证每个节点被选的概率一样.进阶:如果链表十分大且长度未知,如何解决这个问题?你能否使用常数级空间复杂度实现?示例:// 初始化一个单链表 [1,2,3].ListNode head = new ListNode(1);head.next = new ListNode(2);head.next.next = new ListNode(3);Solution solution = new Solution(head);// getRand…
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 effic…
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 effi…
这题参照http://blog.jobbole.com/42550/ 用的蓄水池算法,即更改ans的概率为1/(当前length) /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { private ListNode head; /**…