第90天。
今天的题目是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();
写出了一个朴素的解法,两次扫描:
然后是利用栈来做的一个解法,即一直递归调用直到链表结尾,这时我们已经遍历了一遍链表就可以知道其长度了,在这时生成随机数,然后在递归调用返回的时候通过这个随机数来选取节点:
最后是dicuss
中的水库抽样法:
证明可参考:http://blog.csdn.net/so_geili/article/details/52937212