给定一个正整数数组 w ,其中 w[i] 代表下标 i 的权重(下标从 0 开始),请写一个函数 pickIndex ,它可以随机地获取下标 i,选取下标 i 的概率与 w[i] 成正比。
例如,对于 w = [1, 3],挑选下标 0 的概率为 1 / (1 + 3) = 0.25 (即,25%),而选取下标 1 的概率为 3 / (1 + 3) = 0.75(即,75%)。
也就是说,选取下标 i 的概率为 w[i] / sum(w) 。
来源:力扣(LeetCode)
二分查找
typedef struct
{
int *pre;
int preSize;
int total;
} Solution;
Solution* solutionCreate(int* w, int wSize)
{
Solution *obj = malloc (sizeof (Solution));
obj -> pre = malloc (sizeof (int) * wSize);
obj -> preSize = wSize;
obj -> total = 0;
int i;
for (i = 0; i < wSize; i ++)
{
obj -> total += w[i];
if (i > 0)
{
obj -> pre[i] = obj -> pre[i - 1] + w[i];
}
else
{
obj -> pre[i] = w[i];
}
}
return obj;
}
int
solutionPickIndex(Solution* obj)
{
int x = rand () % obj -> total + 1;
int left = 0;
int right = obj -> preSize - 1;
while (right > left)
{
int mid = left + (right - left) / 2;
if (obj -> pre[mid] < x)
{
left = mid + 1;
}
else
{
right = mid;
}
}
return left;
}
void
solutionFree(Solution* obj)
{
free (obj -> pre);
free (obj);
}
/**
* Your Solution struct will be instantiated and called as such:
* Solution* obj = solutionCreate(w, wSize);
* int param_1 = solutionPickIndex(obj);
* solutionFree(obj);
*/