Formatted question description: https://leetcode.ca/all/382.html
382 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. 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();
The most straightforward method is to first count the length of the linked list, and then randomly generate a position based on the length, and then traverse to this position from the beginning.
In Follow up, it is said that the linked list may be very long, and we cannot know the length in advance. Here we use the famous
Reservoir Sampling idea.
Since head must exist, first let the return value res be equal to the node value of head, then let cur point to the next node of head, define a variable i, initialize it to 2.
- If cur is not empty, start the loop, take a random number in [0, i-1],
- If 0 is taken out, then res is updated to the current node value of cur, and then i is incremented by one and cur points to its next position. This is actually equivalent to maintaining a pond of size 1.
- Then if the random number is generated as 0, exchange the value in the pond and the value currently traversed to ensure that the probability of each number is equal.