leetcode-398-随机数索引-C语言

/*
 * 算法思想:
 * 蓄水池抽样算法,遍历整个数组,根据蓄水池抽样算法,决定当前元素的舍弃或者保留。
 *
 */

typedef struct {
    int *arr; 
    int len;
} Solution;

Solution* solutionCreate(int* nums, int numsSize) {
    int i;
    Solution* obj = (Solution*)malloc(sizeof(Solution));
    obj->arr = nums;
    obj->len = numsSize;

    return obj;
}

int solutionPick(Solution* obj, int target) {
    int i=0;
    int ret = INT_MIN;
    int cnt = 0;
    
    for(i=0; i<obj->len; i++){
        if(obj->arr[i] == target){
            cnt++;
            ret = (rand()%cnt == 0) ? i : ret;
        }   
    }

    return ret;
}

void solutionFree(Solution* obj) {
    free(obj);
}

/**
 * Your Solution struct will be instantiated and called as such:
 * Solution* obj = solutionCreate(nums, numsSize);
 * int param_1 = solutionPick(obj, target);
 
 * solutionFree(obj);
*/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值