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);
 public class Solution {

     int[] nums;
Random r = new Random(); public Solution(int[] nums) {
this.nums = nums;
} public int pick(int target) {
ArrayList<Integer> idxs = new ArrayList<Integer>();
for (int i = ; i < nums.length; i++) {
if (target == nums[i]) {
idxs.add(i);
}
}
return idxs.get(r.nextInt(idxs.size()));
}
}

Simple Reservior Sampling approach

 public class Solution {

     int[] nums;
Random rnd; public Solution(int[] nums) {
this.nums = nums;
this.rnd = new Random();
} public int pick(int target) {
int result = -;
int count = ;
for (int i = ; i < nums.length; i++) {
if (nums[i] != target)
continue;
if (rnd.nextInt(++count) == )
result = i;
} return result;
}
}

Simple Reservior Sampling

Suppose we see a sequence of items, one at a time. We want to keep a single item in memory, and we want it to be selected at random from the sequence. If we know the total number of items (n), then the solution is easy: select an index ibetween 1 and n with equal probability, and keep the i-th element. The problem is that we do not always know n in advance. A possible solution is the following:

  • Keep the first item in memory.
  • When the i-th item arrives (for {\displaystyle i>1}):
    • with probability {\displaystyle 1/i}, keep the new item (discard the old one)
    • with probability {\displaystyle 1-1/i}, keep the old item (ignore the new one)

So:

  • when there is only one item, it is kept with probability 1;
  • when there are 2 items, each of them is kept with probability 1/2;
  • when there are 3 items, the third item is kept with probability 1/3, and each of the previous 2 items is also kept with probability (1/2)(1-1/3) = (1/2)(2/3) = 1/3;
  • by induction, it is easy to prove that when there are n items, each item is kept with probability 1/n.

Random Pick Index的更多相关文章

  1. 398. Random Pick Index - LeetCode

    Question 398. Random Pick Index Solution 思路:重点是如果数据中有多个数target相等,要从这些数中随机取一个,根据例题 假设输入是: int[] nums ...

  2. [LeetCode] Random Pick Index 随机拾取序列

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  3. Leetcode: Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  4. [Swift]LeetCode398. 随机数索引 | Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  5. [LeetCode] 398. Random Pick Index ☆☆☆

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  6. 398. Random Pick Index随机pick函数

    [抄题]: Given an array of integers with possible duplicates, randomly output the index of a given targ ...

  7. [LC] 398. Random Pick Index

    Given an array of integers with possible duplicates, randomly output the index of a given target num ...

  8. 【LeetCode】398. Random Pick Index 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 每次遍历索引 字典保存索引 蓄水池抽样 日期 题目地 ...

  9. [leetcode] 398. Random Pick Index

    我是链接 看到这道题,想到做的几道什么洗牌的题,感觉自己不是很熟,但也就是rand()函数的调用,刚开始用map<int, vector<int >>来做,tle,后来就想着直 ...

随机推荐

  1. xheditor编辑器的使用

    xheditor编辑器的使用 一个博客.cms网站都一定会用到一个html编辑器,刚好xmfdsh在做网站时候需要用到这类编辑器,在对比了之后,发现其实差不了多少,刚好一个不错的friend在用xhe ...

  2. PHPstorm设置连接FTP,进行文件上传、下载、比较

                                                 内容转载自:http://www.cnblogs.com/jikey/p/3486621.html   如何在 ...

  3. C++ security issue analyze

    https://sploitfun.wordpress.com/about-2/ “Happiness is only real when shared” – Into the wild http:/ ...

  4. jsonp解决CORS问题

    jsonp是个机智的解决办法: 1.本地页面写个js方法 <script> function abc(data) { alert(data.result); } </script&g ...

  5. gradle 默认属性

    Properties(未翻译) Property Description allprojects 包含该项目及其子项目的属性 ant The AntBuilder for this project. ...

  6. Class.isAssignableFrom(Class clz)与instanceof与Class.isInstance(Object obj) 的区别和联系

    编程的时候可能会遇到一个不知道它属于哪个类的对象,我们可以用下列运算符或者方法来判断.  1.instanceof instanceof是运算符只被用于对象引用变量,检查左边的被测试对象是不是右边类或 ...

  7. Struts2 自定义拦截器

    自定义拦截器(权限管理),包含了对ajax和表单请求的拦截 package com.interceptor; import java.io.IOException; import java.io.Pr ...

  8. connect() failed (111: Connection refused) while connecting to upstream

    配置好lamp后,在浏览器中运行程序后,出现上面的错误. 转自:http://www.xuejiehome.com/blread-1828.html I'm experiencing 502 gate ...

  9. CLGeocoder "Lost connection to geod" #error# when use geocodeAddressString:completionHandler

      I got this warning when I tried to get destination using CLGeoCoder and the warning is coming out ...

  10. Markdown 學習

    Markdown 格式由John Gruber 創建,是一種便於閱讀,非常簡潔直觀的純文本文件格式,可以方便地轉為html等其他格式,很適合與寫作,不需要關注排版問題 常用學習資源有: ###標題用 ...