Linked List Random Node - Medium - L
Published:
Question
- https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/
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
- LinkedList
Solution
class Solution {
private ListNode head;
/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */
public Solution(ListNode head) {
this.head = head;
}
/** Returns a random node's value. */
public int getRandom() {
int scope = 1, chosenValue = 0;
ListNode curr = this.head;
while (curr != null) {
// decide whether to include the element in reservoir
if (Math.random() < 1.0 / scope)
chosenValue = curr.val;
// move on to the next node
scope += 1;
curr = curr.next;
}
return chosenValue;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/