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();
链表随机节点。
题意是给一个单链表,请随机返回一个node.val。followup是如果链表太大或者size未知怎么处理,需要确保每个元素被返回的几率相同。
思路是水塘抽样。我参考了这个帖子。水塘抽样的思路我举例说明。比如你需要从 [111, 222, 333, 444] 中随机选取3个数字,此时每个数字被选到的几率是3/4。一开始你选了[111, 222, 333],然后你选取444的几率是3/4;对于111来说,他依然留在水塘里的几率 = P(444没有被选到的几率) + P(444被选到但是replace了222或333的几率) = 1/4 + 3/4 * 2/3 = 3/4。对于这道题而言,水塘的size就是1。
时间O(n)
空间O(1)
Java实现
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode() {} 7 * ListNode(int val) { this.val = val; } 8 * ListNode(int val, ListNode next) { this.val = val; this.next = next; } 9 * } 10 */ 11 class Solution { 12 private ListNode head; 13 private Random rmd; 14 15 /** @param head The linked list's head. 16 Note that the head is guaranteed to be not null, so it contains at least one node. */ 17 public Solution(ListNode head) { 18 this.head = head; 19 rmd = new Random(); 20 } 21 22 /** Returns a random node's value. */ 23 public int getRandom() { 24 ListNode temp = head; 25 int res = temp.val; 26 int i = 1; 27 while (temp.next != null) { 28 temp = temp.next; 29 i++; 30 if (rmd.nextInt(i) == 0) { 31 res = temp.val; 32 } 33 } 34 return res; 35 } 36 } 37 38 /** 39 * Your Solution object will be instantiated and called as such: 40 * Solution obj = new Solution(head); 41 * int param_1 = obj.getRandom(); 42 */