LeetCode Linked List Random Node

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

本题要从一个链表中随机取一个数。常规解法是先遍历一遍链表,得到链表长度n,然后rand()%n确定随机取的节点位置,最后遍历链表找到第rand()%n个数。 但是这种解法肯定不是大家想要的,Follow up里提到,如果链表很长,没法提前知道链表长度,该怎么办呢?查阅题解才发现需要用到一个叫做水塘抽样的方法,这篇博客介绍得挺详细的。简单来说,就是假设有n个节点(n提前不知道),我们希望每个节点被采样的概率都是1/n,我们可以这样做,遍历到第i个节点时,以概率1/i采样i号节点。我们来算一算第i号节点被采样的概率=遍历到第i号节点时,要被采样,且后面节点都不被采样,公式为: $$!\frac{1}{i}*\frac{i}{i+1}*\frac{i+1}{i+2}*…*\frac{n-1}{n}=\frac{1}{n}$$ 即每个节点被采样到的概率都等于$$\frac{1}{n}$$。 具体怎样实现以$$\frac{1}{i}$$采样呢,我们可以令k=rand()%i,则k随机分布在[0,i-1],所以k==0的概率就是$$\frac{1}{i}$$。完整代码如下: [cpp] class Solution { private: ListNode* mhead; public: /** @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) { mhead = head; } /** Returns a random node’s value. */ int getRandom() { int ans = mhead->val, n = 2; ListNode* cur = mhead->next; while (cur) { int r = rand() % n; if (r == 0)ans = cur->val; cur = cur->next; ++n; } return ans; } }; [/cpp] 本代码提交AC,用时49MS。]]>

1 thought on “LeetCode Linked List Random Node

  1. Pingback: LeetCode Random Pick Index | bitJoy > code

Leave a Reply

Your email address will not be published. Required fields are marked *