Sponsored
Sponsored
This method involves converting the linked list into an array during the initialization of the Solution
object. Once the linked list is stored as an array, we can easily obtain a random node's value by selecting a random index in the array. This guarantees each node has an equal probability of being chosen.
Time Complexity: O(N) for preprocessing, O(1) for getRandom
.
Space Complexity: O(N) for storing the list in an array.
1#include <vector>
2#include <cstdlib>
3
4struct ListNode {
5 int val;
6 ListNode *next;
7 ListNode(int x) : val(x), next(nullptr) {}
8};
9
10class Solution {
11 std::vector<int> values;
12public:
13 Solution(ListNode* head) {
14 ListNode* node = head;
15 while (node) {
16 values.push_back(node->val);
17 node = node->next;
18 }
19 }
20
21 int getRandom() {
22 int randomIndex = std::rand() % values.size();
23 return values[randomIndex];
24 }
25};
The C++ solution uses a std::vector
to store linked list values during initialization. The getRandom
method selects a random index from this vector, ensuring uniform probability among nodes.
Reservoir Sampling is an efficient algorithm that allows you to randomly select a single item from a stream (or a linked list) of unknown length with all items having an equal probability. You can accomplish this by traversing the linked list node by node, replacing the selected item with decreasing probability.
Time Complexity: O(N) for getRandom
.
Space Complexity: O(1).
1
This C solution applies reservoir sampling to randomly select a node from the linked list. For each node, with probability 1/count, the current node value is chosen as the reservoir value, allowing us to accomplish this in one pass with constant space.