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号节点时,要被采样,且后面节点都不被采样,公式为:
Pingback: LeetCode Random Pick Index | bitJoy > code