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();
要求从单链表中,随机返回一个节点的值,要求每一个节点被选中的几率是相等的。java
在等几率随机选择算法中,最经典的算法就是蓄水池算法。能够参考同类型题目398 random pick index。这里再次整理一下蓄水池算法的思路和简单证实。node
假如一共有N个物品,须要从其中挑选出K个物品,要求确保N个物品中每一个物品都可以被等几率选中。对于这种等几率问题,简答的作法是经过随机数获取选中物品的下标。可是蓄水池算法容许咱们从数据流的角度来随机得到K个物品,即在并不知道整体的样本数有多少的状况下,随机抽取K个物品。算法
蓄水池算法的思路以下:segmentfault
K/(K+1)
K/(K+i)
对于这个算法,咱们能够采用概括法进行简单证实。已知对于前K个物品,每一个物品的被选中的几率为1,知足了K/K=1
的几率。
对于K+i-1个物品,假设每一个物品被选中的几率为K/(K+i-1)
。证实对于前K+i个物品,每一个物品被放入蓄水池中的几率为K/(K+i)
dom
K/(K+i)
P = P(上一轮在蓄水池中) * P(这一轮没有被替换掉)
。对此进行计算,P(上一轮在蓄水池中) * P(这一轮没有被替换掉) = P(上一轮在蓄水池中) * (1-P(这一轮被替换掉)) = (K / (K+i-1)) * (1 - (P * 1/K))
,算出P = K/(K+i)
K/(K+i)
,当K+i等于N时,每一个物品被选中的几率为K/N
在本题中,使用蓄水池算法的N为单链表的长度,K为1。this
代码以下:spa
private ListNode head; private Random r; /** @param head The linked list's head. Note that the head is guaranteed to be not null, so it contains at least one node. */ public Solution(ListNode head) { this.head = head; this.r = new Random(); } /** Returns a random node's value. */ public int getRandom() { ListNode tmp = this.head; int result = 0; int index = 1; do{ if(r.nextInt(index) == 0) { result = tmp.val; } tmp = tmp.next; index++; }while(tmp != null); return result; }