382 Linked List Random Node

1. Question

Given a singly linked list, return a random node's value from the linked list. Each node must have thesame probabilityof 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:
1
// Init a singly linked list [1,2,3].
2
ListNode head = new ListNode(1);
3
head.next = new ListNode(2);
4
head.next.next = new ListNode(3);
5
Solution solution = new Solution(head);
6
7
// getRandom() should return either 1, 2, or 3 randomly. Each element should have equal probability of returning.
8
solution.getRandom();
Copied!

2. Implementation

(1) Reservoir Sampling
1
/**
2
* Definition for singly-linked list.
3
* public class ListNode {
4
* int val;
5
* ListNode next;
6
* ListNode(int x) { val = x; }
7
* }
8
*/
9
class Solution {
10
Random rand;
11
ListNode head;
12
13
/** @param head The linked list's head.
14
Note that the head is guaranteed to be not null, so it contains at least one node. */
15
public Solution(ListNode head) {
16
this.head = head;
17
rand = new Random();
18
}
19
20
/** Returns a random node's value. */
21
public int getRandom() {
22
ListNode curNode = head;
23
int res = head.val;
24
25
for (int i = 1; curNode != null; i++, curNode = curNode.next) {
26
if (rand.nextInt(i) == 0) {
27
res = curNode.val;
28
}
29
}
30
return res;
31
}
32
}
33
34
/**
35
* Your Solution object will be instantiated and called as such:
36
* Solution obj = new Solution(head);
37
* int param_1 = obj.getRandom();
38
*/
Copied!

3. Time & Space Complexity

Reservoir Sampling: 时间复杂度O(n), 空间复杂度O(1)