https://leetcode.cn/problems/random-pick-index/
根据题目所知,所给的数组中有重复的元素。让我们随机输出给定的目标数字的下标索引。
typedef struct {
int *sum;
int length;
} Solution;
Solution* solutionCreate(int* nums, int numsSize) {
Solution* obj = (Solution*)malloc(sizeof(Solution));
obj->sum = nums;
obj->length = numsSize;
return obj;
}
int solutionPick(Solution* obj, int target) {
int count = 0;
int *num = (int*)malloc(sizeof(int)*obj->length);
for(int i = 0; i< obj->length ; i++)
{
if(target == obj->sum[i])
{
num[count++] = i;
}
}
int ret = num[rand() % count];
free(num);
return ret;
}
void solutionFree(Solution* obj) {
free(obj);
}