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();
Analysis:
One way is reservoir sampling: https://en.wikipedia.org/wiki/Reservoir_sampling
Solution:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 ListNode first; 11 12 /** @param head The linked list's head. 13 Note that the head is guaranteed to be not null, so it contains at least one node. */ 14 public Solution(ListNode head) { 15 first = head; 16 } 17 18 /** Returns a random node's value. */ 19 public int getRandom() { 20 ListNode target = first; 21 int val = target.val; 22 Random engine = new Random(); 23 for (int i=1;target!=null;i++){ 24 if (engine.nextInt(i)==0){ 25 val = target.val; 26 } 27 target = target.next; 28 } 29 return val; 30 } 31 } 32 33 /** 34 * Your Solution object will be instantiated and called as such: 35 * Solution obj = new Solution(head); 36 * int param_1 = obj.getRandom(); 37 */
Solution 2: Regular answer
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 11 Map<Integer,Integer> indexMap; 12 int index; 13 14 /** @param head The linked list's head. 15 Note that the head is guaranteed to be not null, so it contains at least one node. */ 16 public Solution(ListNode head) { 17 indexMap = new HashMap<Integer,Integer>(); 18 index = 0; 19 ListNode cur = head; 20 while (cur!=null){ 21 indexMap.put(index,cur.val); 22 index++; 23 cur = cur.next; 24 } 25 } 26 27 /** Returns a random node's value. */ 28 public int getRandom() { 29 Random engine = new Random(); 30 int ind = engine.nextInt(index); 31 return indexMap.get(ind); 32 } 33 } 34 35 /** 36 * Your Solution object will be instantiated and called as such: 37 * Solution obj = new Solution(head); 38 * int param_1 = obj.getRandom(); 39 */