382. Linked List Random Node
https://leetcode.com/problems/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.
Approach 1 : Reservoir Sampling
Walk through all .
For each node, if rand() % len == 0
, set the current value to the answer.
Proof:
-
For the last node n, the probability is obviously .
So the probability of left nodes is .
-
For the n-1 node, the probability is $ \frac{n-1}{n}*\frac{1}{n-1} = \frac{1}{n} $ .
So the probability of left nodes is .
-
For the n-2 node. the probability is $ \frac{n-2}{n}*\frac{1}{n-2} = \frac{1}{n} $
So the probability of left nodes is .
-
Similarly, we can prove that:
For ANY node, the probability is .
class Solution {
public:
ListNode* u;
Solution(ListNode* head) {
u = head;
}
dd
int getRandom() {
int res, len = 1;
ListNode* v = u;
while(v){
if(rand() % len == 0){
res = v->val;
}
len++;
v = v->next;
}
return res;
}
};
Runtime: 36 ms, faster than 87.72% of C++ online submissions for Linked List Random Node.
Memory Usage: 16.5 MB, less than 50.00% of C++ online submissions for Linked List Random Node.
Complexity Analysis
- Time complexity :
- Space complexity :