LeetCode 382. Linked List Random Node
来源:互联网 发布:铁路 纪录片 知乎 编辑:程序博客网 时间:2024/05/16 04:51
题目描述:
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 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();
题目大意:
给定一个单链表,返回链表中一个随机节点的值。每一个节点应该被等可能的抽取。
进一步思考:
如果链表很大并且长度未知呢?你可以不使用额外的空间高效地解决此问题吗?
解题思路:
蓄水池抽样(Reservoir Sampling)
蓄水池抽样算法的等概率性可以用数学归纳法证明:
I 当链表长度为1时,random.randint(0, 0)恒等于0,因此抽到第1个元素的概率为1II 假设抽取前n个元素的概率相等,均为1/nIII 当抽取第n+1个元素时:若random.randint(0, n)等于0,则返回值替换为第n+1个元素,其概率为1/(n+1);否则,抽取的依然是前n个元素,其概率为1/n * n/(n+1) = 1/(n+1)
Python代码:
import randomclass Solution(object): def __init__(self, head): “”” @param head The linked list’s head. Note that the head is guanranteed to be not null, so it contains at least one node. :type head: ListNode “”“ self.head = head def getRandom(self): “”” Returns a random node’s value. :rtype: int “”“ cnt = 0 head = self.head while head: if random.randint(0, cnt) == 0: ans = head.val head = head.next cnt += 1 return ans
本文链接:http://bookshadow.com/weblog/2016/08/10/leetcode-linked-list-random-node/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。
如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码
阅读全文
0 0
- [leetcode] 382. Linked List Random Node
- <LeetCode OJ> 382. Linked List Random Node
- LeetCode—382. Linked List Random Node
- 【leetcode】382. Linked List Random Node
- [leetcode]382. Linked List Random Node
- Leetcode 382. Linked List Random Node
- [LeetCode]382. Linked List Random Node
- LeetCode 382. Linked List Random Node
- [leetcode]382. Linked List Random Node
- [Leetcode]382. Linked List Random Node
- 【LeetCode】 382. Linked List Random Node
- [leetcode]382. Linked List Random Node
- LeetCode 382. Linked List Random Node
- [LeetCode]382. Linked List Random Node
- leetcode 382. Linked List Random Node
- [LeetCode] 382. Linked List Random Node
- LeetCode 382. Linked List Random Node
- leetcode 382. Linked List Random Node
- java深入学习六之正则表达式
- Python 中的random函数
- Apache Beam的分窗与触发器
- Windows系统中搭建Spark开发环境
- Qt实现一个简单的打字游戏
- LeetCode 382. Linked List Random Node
- html和CSS基础学习(六)
- input框placeholder样式修改
- 2017 ACM-ICPC乌鲁木齐网络赛 G. Query on a string 【KMP+树状数组】
- POJ 1873 The Fortified Forest(凸包+状态枚举)
- S5PV210 启动流程
- 顺序表应用2:多余元素删除之建表算法
- 设计模式享元模式
- HDU 1372Knight Moves(bfs)