有趣的随机算法

一. 蓄水池抽样算法

leetcode 382. 链表随机节点
题目链接

本题新奇之处在于在链表中查找随机一个数。
每次只保留一个数,当遇到第 i个数时,以 1/i的概率保留它,(i-1)/i的概率保留原来的数。
这样每个节点概率就相等了

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* h;
    Solution(ListNode* head) {
        h=head;
    }
    
    int getRandom() {
        int n=0;
        int c=-1;
        for(auto p=h;p;p=p->next)
        {
            n++;
            if(rand()%n==0)c=p->val;
        }
        return c;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(head);
 * int param_1 = obj->getRandom();
 */

二. Fisher-Yates 洗牌算法

leetcode 384. 打乱数组
题目链接

class Solution {
public:
    vector<int>nums;
    Solution(vector<int>& a) {
        nums=a;
    }
    
    vector<int> reset() {
        return nums;
    }
    
    vector<int> shuffle() {
        auto b=nums;
        int n=nums.size();
        for(int i=0;i<n;i++)
        {
            swap(b[i],b[i+rand()%(n-i)]);
        }
        return b;
    }
};

/**
 * Your Solution object will be instantiated and called as such:
 * Solution* obj = new Solution(nums);
 * vector<int> param_1 = obj->reset();
 * vector<int> param_2 = obj->shuffle();
 */
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_WAWA鱼_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值