当前位置:网站首页>398. 随机数索引-哈希表法
398. 随机数索引-哈希表法
2022-07-23 16:30:00 【Mr Gao】
398. 随机数索引
给你一个可能含有 重复元素 的整数数组 nums ,请你随机输出给定的目标数字 target 的索引。你可以假设给定的数字一定存在于数组中。
实现 Solution 类:
Solution(int[] nums) 用数组 nums 初始化对象。
int pick(int target) 从 nums 中选出一个满足 nums[i] == target 的随机索引 i 。如果存在多个有效的索引,则每个索引的返回概率应当相等。
示例:
输入
[“Solution”, “pick”, “pick”, “pick”]
[[[1, 2, 3, 3, 3]], [3], [1], [3]]
输出
[null, 4, 0, 2]
解释
Solution solution = new Solution([1, 2, 3, 3, 3]);
solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。
solution.pick(1); // 返回 0 。因为只有 nums[0] 等于 1 。
solution.pick(3); // 随机返回索引 2, 3 或者 4 之一。每个索引的返回概率应该相等。
解题代码如下:
typedef struct {
long long index;
long long val;
struct Solution *next;
} Solution;
Solution* solutionCreate(int* nums, int numsSize) {
Solution *l=(Solution *)malloc(sizeof(Solution)*10000);
int i;
for(i=0;i<10000;i++){
(l+i)->next=NULL;
}
for(i=0;i<numsSize;i++){
Solution *p=(Solution *)malloc(sizeof(Solution));
p->index=i;
p->val=nums[i];
p->next=(l+abs(nums[i])%10000)->next;
(l+abs(nums[i])%10000)->next=p;
}
return l;
}
int solutionPick(Solution* obj, int target) {
Solution * p=(obj+abs(target)%10000)->next;
int count=0;
int pc=rand();
while(p){
if(p->val==target){
count++;
}
p=p->next;
}
pc=pc%count;
int cz=0;
p=(obj+abs(target)%10000)->next;
while(p){
if(p->val==target){
if(cz==pc){
return p->index;
}
cz++;
}
p=p->next;
}
return -1;
}
void solutionFree(Solution* obj) {
}
/** * Your Solution struct will be instantiated and called as such: * Solution* obj = solutionCreate(nums, numsSize); * int param_1 = solutionPick(obj, target); * solutionFree(obj); */
边栏推荐
- opencv(13):cv2.findContours、cv::findContours简要介绍及opencv各版本cv2.findContours函数说明
- Boss online replay: the mistake I made when training Dall · e
- Where should we start to learn modeling from zero foundation? How to learn game modeling well?
- MySQL性能调优
- Three things programmers want to do most | comics
- Common problems of sklearn classifier
- 从业务开发中学习和理解架构设计
- 华为胖瘦AP切换方法
- Behind the recovery of the B-END Market: who stands in front of the stage?
- awk从入门到入土(16)awk综合案例
猜你喜欢

What problems do you usually encounter when learning 3D modeling? It's too much

到底适不适合学习3D建模?这5点少1个都不行

How to capture the analyst rating data of Sina Financial Data Center?

rhcsa笔记七

悲观锁和乐观锁

【重磅】聚焦券商终端业务,博睿数据发布新一代券商终端核心业务体验可观测平台

大神“魔改”AirPods,配备USB-C接口,3D打印外壳让维修更容易

入门学习3D建模一般会遇到哪些问题?实在是太多了

serialization and deserialization

VS2010一个解决方案下新建多个项目出现的问题和方法
随机推荐
防控调整后暑期市场井喷,途家、木鸟、美团暑期活动测评
Flame Graphs 火焰图安装与使用
Rhcsa notes 5
Rhcsa notes 7
零一的昔日织-2022
零基础要学建模该从何开始?如何才能学好游戏建模?
搭建PHP开发环境(Apache+PHP+MySQL)「建议收藏」
Flutter operation mode
一文详解:TMP1750芯片 三通道线性LED驱动器
Foundation of class
Interface test overview
【Coggle 30 Days of ML】糖尿病遗传风险检测挑战赛(2)
从业务开发中学习和理解架构设计
MySQL classic exercises and answers, 50 common SQL sentence exercises
Flink Exactly-Once 投递实现浅析
PCL:多直线拟合(RANSAC)
What happened behind kubectl's creation of pod?
rhcsa笔记五
【游戏建模模型制作全流程】用ZBrush制作游戏士兵角色
The Little Schemer-周而复始之Y组合子由来