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