Leetcode 382. Linked List Random Node
Given a singly linked list, the task is to write a function that returns a random node’s value from the linked list. Each node must have the same probability of being chosen.
You need to implement the Solution
class:
Solution(ListNode head)
Initializes the object with the head of the singly-linked list head
.int getRandom()
Chooses a node randomly from the list and returns its value. All the nodes of the list should be equally likely to be chosen.public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
To ensure every node has the same probability of being chosen, we can implement a solution using Reservoir Sampling. Here’s the approach:
Solution(ListNode head)
)
getRandom()
)
rand.nextInt(i + 1)
where i
is the index of the current node. This ensures each node has a 1/(i+1)
chance of being chosen.import java.util.Random;
public class Solution {
private ListNode head;
private Random rand;
/** @param head The linked list's head. */
public Solution(ListNode head) {
this.head = head;
this.rand = new Random();
}
/** Returns a random node's value. */
public int getRandom() {
ListNode current = head;
int result = current.val;
int index = 1;
while (current.next != null) {
current = current.next;
if (rand.nextInt(index + 1) == 0) {
result = current.val;
}
index++;
}
return result;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
This solution ensures that each node in the linked list has an equal probability of being chosen by utilizing reservoir sampling.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?