leetcode528. 按权重随机选择

Dear 丶 2022-09-09 11:52 216阅读 0赞

在这里插入图片描述
思路

  1. 权重模拟
    在这里插入图片描述

    typedef struct {

    1. int max;
    2. int count;
    3. int w[10001];

    } Solution;

  1. Solution* solutionCreate(int* w, int wSize) {
  2. Solution* t = (Solution*)malloc(sizeof(Solution));
  3. t->max =0;
  4. t->count = wSize;
  5. int i;
  6. for(i=0;i<wSize;i++){
  7. t->w[i] = w[i];
  8. t->max += w[i];
  9. }
  10. return t;
  11. }
  12. int solutionPickIndex(Solution* obj) {
  13. int t =rand()%(obj->max)+1;
  14. int i;
  15. for(i=0;i<obj->count;i++){
  16. if(t>obj->w[i])
  17. t-=obj->w[i];//相减,以长度关系模拟区间
  18. else
  19. break;
  20. }
  21. return i;
  22. }
  23. void solutionFree(Solution* obj) {
  24. free(obj);
  25. }
  26. /** * Your Solution struct will be instantiated and called as such: * Solution* obj = solutionCreate(w, wSize); * int param_1 = solutionPickIndex(obj); * solutionFree(obj); */

发表评论

表情:
评论列表 (有 0 条评论,216人围观)

还没有评论,来说两句吧...

相关阅读

    相关 528. 随机选择

    给定一个正整数数组 w ,其中 w\[i\] 代表下标 i 的权重(下标从 0 开始),请写一个函数 pickIndex ,它可以随机地获取下标 i,选取下标 i 的概率与 w

    相关 css选择

    第一等:代表内联样式,如: style=””,权值为1000。 第二等:代表ID选择器,如:\content,权值为100。 第三等:代表类,伪类和属性选择器,如 .c

    相关 值的随机选择算法

    一个新的功能上线都会走灰度的过程,万一新功能有问题,则会导致线上的大量的报错,甚至不可用的严重情况。比如我们现在本来接入了2个短信渠道去发送短信,现在接入好了第三个渠道,如果我