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


原创粉丝点击