zoukankan      html  css  js  c++  java
  • Leetcode: Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target number. You can assume that the given target number must exist in the array.
    
    Note:
    The array size can be very large. Solution that uses too much extra space will not pass the judge.
    
    Example:
    
    int[] nums = new int[] {1,2,3,3,3};
    Solution solution = new Solution(nums);
    
    // pick(3) should return either index 2, 3, or 4 randomly. Each index should have equal probability of returning.
    solution.pick(3);
    
    // pick(1) should return 0. Since in the array only nums[0] is equal to 1.
    solution.pick(1);

    Three types of answer:

    1. Map Solution, O(N) memory, O(N) init, O(1) pick.

    2. Like @dettier's Reservoir Sampling. O(1) init, O(1) memory, but O(N) to pick.

    Reservior Sampling

     1 public class Solution {
     2     int[] arr;
     3     Random random;
     4     
     5 
     6     public Solution(int[] nums) {
     7         arr = nums;
     8         random = new Random();
     9     }
    10     
    11     public int pick(int target) {
    12         int count = 0;
    13         int index = 0;
    14         for (int i=0; i<arr.length; i++) {
    15             if (arr[i] == target) {
    16                 count++;
    17                 if (random.nextInt(count) == 0) {
    18                     index = i;
    19                 }
    20             }
    21         }
    22         return index;
    23     }
    24 }
    25 
    26 /**
    27  * Your Solution object will be instantiated and called as such:
    28  * Solution obj = new Solution(nums);
    29  * int param_1 = obj.pick(target);
    30  */

    Map solution: MLE for big case

     1 public class Solution {
     2 
     3     public Solution(int[] nums) {
     4         for (int i=0; i<nums.length; i++) {
     5             int num = nums[i];
     6             if (!indexes.containsKey(num))
     7                 indexes.put(num, new ArrayList<Integer>());
     8             indexes.get(num).add(i);
     9         }
    10     }
    11     
    12     public int pick(int target) {
    13         List<Integer> indexes = this.indexes.get(target);
    14         int i = (int) (Math.random() * indexes.size());
    15         return indexes.get(i);
    16     }
    17     
    18     private Map<Integer, List<Integer>> indexes = new HashMap<>();
    19 }
  • 相关阅读:
    《洛谷P2296 寻找道路》
    《浙江科技学院第17届大学生程序设计竞赛:D:合并序列》
    《数论整理二》
    《洛谷P1282 多米诺骨牌》
    《洛谷P2140 小Z的电力管制》
    《洛谷P2798 爆弹虐场》
    Linux下运行C语言程序
    计算圆柱的底面积和体积
    将摄氏温度转化为华氏温度
    如果今天是星期二,那么100天后是星期几?
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/6117236.html
Copyright © 2011-2022 走看看