Advertisement
1988coder

382. Linked List Random Node

Jan 27th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.72 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/linked-list-random-node/
  3. import java.util.Random;
  4.  
  5. //   Definition for singly-linked list.
  6. class ListNode {
  7.     int val;
  8.     ListNode next;
  9.  
  10.     ListNode(int x) {
  11.         val = x;
  12.     }
  13. }
  14.  
  15. /**
  16.  * Reservoir Sampling
  17.  *
  18.  * Suppose there are 1 to N numbers in the list. You have already picked i-1
  19.  * elements. Now you are trying to pick ith element. The probability to pick it
  20.  * is 1/i. Now you do not want to pick any future numbers.. Thus, the final
  21.  * probability for ith element = 1/i * (1 - 1/(i+1)) * (1 - 1/(i+2)) * .. * (1 -
  22.  * 1/N) = 1 / N.
  23.  *
  24.  * Time Complexity: 1) Solution() -> O(1).. 2) pick() -> O(N)
  25.  *
  26.  * Space Complexity: O(1)
  27.  *
  28.  * N = Length of the input array.
  29.  */
  30. class Solution {
  31.  
  32.     ListNode listHead;
  33.     Random rand;
  34.  
  35.     /**
  36.      * @param head The linked list's head. Note that the head is guaranteed to be
  37.      *             not null, so it contains at least one node.
  38.      */
  39.     public Solution(ListNode head) {
  40.         if (head == null) {
  41.             return;
  42.         }
  43.         listHead = head;
  44.         rand = new Random();
  45.     }
  46.  
  47.     /** Returns a random node's value. */
  48.     public int getRandom() {
  49.         if (listHead == null) {
  50.             return -1;
  51.         }
  52.  
  53.         ListNode cur = listHead;
  54.         int result = cur.val;
  55.         int count = 1;
  56.  
  57.         while (cur.next != null) {
  58.             cur = cur.next;
  59.             count++;
  60.             if (rand.nextInt(count) == 0) {
  61.                 result = cur.val;
  62.             }
  63.         }
  64.  
  65.         return result;
  66.     }
  67. }
  68.  
  69. /**
  70.  * Your Solution object will be instantiated and called as such: Solution obj =
  71.  * new Solution(head); int param_1 = obj.getRandom();
  72.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement