leetcode_middle_38_398. Random Pick Index
来源:互联网 发布:mac打开远程桌面连接 编辑:程序博客网 时间:2024/06/07 13:29
题意:
给出一个数,在数组中查找这个数,并随机等概率返回一个这个数的角标。
分析:
这个题在leetcode中属于一类题型,比较优的解法我认为比较简单但是是比较难想的。但是由于我已经做过一道这样的题,知道方法,就没障碍了。回顾一下这个概率方法:
我们要在一列n个数中选一个数,要求每一个数被选中的概率都是1/n,由于我们不想存储,有什么办法一边遍历一边确定呢?
那么一定是出来一个就要选一次,比如5个数,出来3个数了,就已经选了3次了,第4个数还要选。那么概率是什么呢?
比如第四个数被选的时候概率是p4,第5个数被选的时候概率是p5,我们知道一个数如果后面还要选择(扩大样本范围,概率是会被后面所影响的)。
但是第5个数是最后一个数,后面没有了,概率就不会被影响,所以概率必然是1/5,好了,那么第四个呢?就是p4*(1 - 1/5),意思就是第五次没有选中第五个(也即是选中了前四个)再乘上p4(前四个里面选中p4的概率)就是最终选定第4个的概率,而由于这个概率是1/5,我们解等式p4*(1-1/5) = 1/5 => p4=1/4,同理可知顺序遍历动态选择第n个的时候概率应该是1/n.
代码:
public class Solution { int[] nums; Random random; public Solution(int[] nums) { this.nums = nums; random = new Random(); } public int pick(int target) { int r = 0; for(int i=0,j=1; i<nums.length; i++){ //j代表第j次选择 if(nums[i] == target){ if(random.nextInt(j) == 0){ //if(1/j的概率) r = i; } j++; } } return r; }}
0 0
- leetcode_middle_38_398. Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- Random Pick Index
- Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index**
- leetcode398: Random Pick Index
- 398. Random Pick Index
- Random Pick Index
- 398. Random Pick Index
- 398. Random Pick Index
- 【Leetcode】398. Random Pick Index
- Leetcode 398. Random Pick Index
- Python scrapy插入mysql的一个错误TypeError
- 深入理解JVM(七)——Class文件结构
- PAT A1041. Be Unique (20)
- tar包成多个文件
- webservice中遇到的一些问题
- leetcode_middle_38_398. Random Pick Index
- 最长回文子串:manacher算法
- Oracle收购Apiary来加强其API集成云
- Java中this使用的小总结
- 移动测试基础 Android 常用 adb 命令总结
- Linux机器添加互信脚本
- Channel Allocation poj1129 (深搜/四色/枚举)
- 新手福音︱正则表达式小工具RegExr
- POJ 3916 Duplicate Removal G++