Advertisement
1988coder

398. Random Pick Index

Jan 27th, 2019
130
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/random-pick-index/
  3. import java.util.Random;
  4.  
  5. /**
  6.  * Reservoir Sampling
  7.  *
  8.  * Suppose the indexes of the target element in array are from 1 to N. You have
  9.  * already placed i-1 elements. Now you are trying to place ith element. The
  10.  * probability to place it at an index between 1 & i is 1/i. Now you do not want
  11.  * to replace ith number by any future numbers.. Thus, the final probability for
  12.  * ith element = 1/i * (1 - 1/(i+1)) * (1 - 1/(i+2)) * .. * (1 - 1/N) = 1 / N.
  13.  *
  14.  * Time Complexity: 1) Solution() -> O(1).. 2) pick() -> O(N)
  15.  *
  16.  * Space Complexity: O(1)
  17.  *
  18.  * N = Length of the input array.
  19.  */
  20. class Solution {
  21.  
  22.     int[] numsArr;
  23.     Random rand;
  24.  
  25.     public Solution(int[] nums) {
  26.         if (nums == null) {
  27.             return;
  28.         }
  29.         numsArr = nums;
  30.         rand = new Random();
  31.     }
  32.  
  33.     public int pick(int target) {
  34.         if (numsArr == null || numsArr.length == 0) {
  35.             return -1;
  36.         }
  37.  
  38.         int count = 0;
  39.         int result = -1;
  40.         for (int i = 0; i < numsArr.length; i++) {
  41.             if (numsArr[i] == target) {
  42.                 count++;
  43.                 if (rand.nextInt(count) == 0) {
  44.                     result = i;
  45.                 }
  46.             }
  47.         }
  48.  
  49.         return result;
  50.     }
  51. }
  52.  
  53. /**
  54.  * Your Solution object will be instantiated and called as such: Solution obj =
  55.  * new Solution(nums); int param_1 = obj.pick(target);
  56.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement