Question

398. Random Pick Index

Solution

思路:重点是如果数据中有多个数target相等,要从这些数中随机取一个,根据例题

假设输入是:
int[] nums = new int[]{1, 2, 3, 3, 3};
int target = 3; 模拟:
1 != target pass
2 != target pass
3 == target pick的概率 nextInt(1)==0的概率 1,返回这个index的概念是1 - 1/3 -1/3 = 1/3
3 == target pick的概率 nextInt(2)==0的概率 1/2, 返回这个index的概率是1/2 * 2/3 = 1/3
3 == target pick的概率 nextInt(3)==0的概率 1/3, 返回这个index的概率是1/3

Java实现:

class Solution {
private int[] nums;
private Random random; public Solution(int[] nums) {
this.nums = nums;
random = new Random();
} public int pick(int target) {
int index = -1;
int count = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i] == target && random.nextInt(++count) == 0) {
index = i;
}
}
return index;
}
} /**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/

Reference

最新文章

  1. 你真的了解UITabBarController吗?
  2. 你真的了解UITableViewCell重用吗?
  3. SOA 架构中的ESB是更好的应用于异构系统集成整合还是用于统一服务调用/基础服务实施
  4. JS手机访问PC端网站自动跳转到手机端网站
  5. Unity的安装和破解
  6. 【服务器防护】VPN的ip变更,导致无法连接服务器,解决方法【阿里云ECS】
  7. 微软在 .NET 3.5 新增了一个 HashSet 类,在 .NET 4 新增了一个 SortedSet 类,本文介绍他们的特性,并比较他们的异同。
  8. Shell编程速查手册
  9. 【iOS知识学习】_iOS沙盒机制
  10. postgreSQL-如何查数据库表、字段以及字段类型、注释等信息?
  11. Java :内部类基础详解
  12. RedHat/Fedora/Centos 下bash 自动补全命令
  13. JS(原生js和jq方式)获取元素属性(自定义属性),删除属性(自定义属性)
  14. Windows下安装Redis客户端
  15. mysql常见问题处理
  16. Ubuntu16.04 下 hadoop的安装与配置(伪分布式环境)
  17. redis详解(三)-- 面试题(转载)
  18. Linux基础知识之用户和用户组以及 Linux 权限管理
  19. jquery的clone方法应用于textarea和select的bug修复不能copy值,clone id重复的解决
  20. String.Split()函数 多种使用实例

热门文章

  1. 10本 Linux PDF 书籍免费分享
  2. UP9616移动电源快充案例
  3. PCB各层的含义
  4. 微信小程序:自定义组件的数据传递
  5. java中switch结构和 while for循环的用法
  6. 每日学习+AS小相册+导入图片标红的原因
  7. Spring MVC框架搭建及其详解
  8. vue简单的父子组件之间传值
  9. input type=&#39;file&#39;限制上传文件类型
  10. git clone 遇到的问题