leetcode 398. Random Pick Index
来源:互联网 发布:网络荐股诈骗 编辑:程序博客网 时间:2024/05/17 23:15
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);
package leetcode;import java.util.Random;public class Random_Pick_Index_398 {int[] nums;Random random;public Random_Pick_Index_398(int[] nums){this.nums=nums;random=new Random();} public int pick(int target) { int count=0; int resultIndex=-1; for(int i=0;i<nums.length;i++){ if(nums[i]==target){ count++; int r=random.nextInt(count); if(r==count-1){ resultIndex=i; } } } return resultIndex; } public static void main(String[] args) {// TODO Auto-generated method stubint[] nums=new int[]{1,2,3,3,3};Random_Pick_Index_398 r=new Random_Pick_Index_398(nums);System.out.println(r.pick(3));}}
random.nextInt(count)指在[0,count)之间随机地选取一个整数。代码中不一定要 r==count-1,其实可以写成 r==0,因为只要保证当前概率是 1/count 即可。
举例,如果target有三个索引:1,2,3。
一开始,1被选中的概率是1。
然后到2。 此时2被选中的概率是1/2。 2不被选中,仍然是1被选中的概率是1/2。
然后到3。 此时3被选中的概率是1/3。 3不被选中,保持之前选中的2的概率是2/3 * 1/2 = 1/3 。
3不被选中,保持之前选中的1的概率是2/3 * 1/2 = 1/3 。
阅读全文
0 0
- 【Leetcode】398. Random Pick Index
- Leetcode 398. Random Pick Index
- [LeetCode] 398. Random Pick Index
- LeetCode 398. Random Pick Index
- [Leetcode]398. Random Pick Index
- 【Leetcode】398. Random Pick Index
- 【LeetCode】 398. Random Pick Index
- LeetCode 398. Random Pick Index
- [leetcode]398. Random Pick Index
- [LeetCode]398. Random Pick Index
- Leetcode-398. Random Pick Index
- [leetcode] 398. Random Pick Index
- leetcode 398. Random Pick Index
- [LeetCode] 398. Random Pick Index
- leetcode 398. Random Pick Index
- LeetCode—398. Random Pick Index
- 【leetcode】398. Random Pick Index【M】
- [leetcode] 398. Random Pick Index 解题报告
- java中的构造方法,类方法和方法
- ConcurrentHashMap
- 【react】页面中引用本地图片
- springMVC表单标签 <form:select>如何禁用下拉列表
- 关于LOD Group的网页链接
- leetcode 398. Random Pick Index
- PDF文件如何添加书签功能
- windows下创建的txt,在mac下是乱码的问题。
- SHUOJ报数问题
- Mac apache
- 怎样快速学习一门新技术
- android 资源文件添加空格/tab/换行
- Ubuntu12.04下FL2440开发环境的搭建
- Spring AOP : Advice 声明 (通知注解)