Linked List Random Node问题及解法
来源:互联网 发布:珠宝设计绘图软件 编辑:程序博客网 时间:2024/05/23 19:20
问题描述:
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?
示例:
// 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)的证明,了解之后,将 k 设置为 1.
过程详见代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: int num;ListNode* hd;double t;/** @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) {num = 0;hd = head; srand((unsigned)time(NULL));}/** Returns a random node's value. */int getRandom() { ListNode* head = hd;int res = head->val;num = 1;head = head->next;while (head){num++;t = (rand() % num + 1) / (double) (num);if (t <= (1.0 / num))res = head->val;head = head->next;}return res;}};/** * Your Solution object will be instantiated and called as such: * Solution obj = new Solution(head); * int param_1 = obj.getRandom(); */
阅读全文
0 0
- Linked List Random Node问题及解法
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- Linked List Random Node
- 【Leetcode】Linked List Random Node
- 382. Linked List Random Node
- LeetCode - Linked List Random Node
- 382. Linked List Random Node
- [leetcode]-Linked List Random Node
- 148. Linked List Random Node
- 382. Linked List Random Node
- TCP/IP、Http、Socket的区别以及面试中关于网络协议常问的考点
- 大数据学习5:hdfs和yarn 的学习记录
- JavaScript中的ERROR对象技术详解
- Unity 鼠标跟随点击位置
- Qt中tcp传输文件遇到的问题
- Linked List Random Node问题及解法
- Maven学习记录3——创建、编译、打包、运行项目
- 机器学习笔记4:TensorFlow基础入门介绍
- Effective STL学习笔记-条款13|14
- 富文本编辑器的使用
- .net redis数据缓存(一) redis在Windows环境中的安装
- 使用Hanlder的注意事项
- Session.load()和get()方法区别
- 【PAT】【Advanced Level】1077. Kuchiguse (20)