游戏中的随机抽样算法

相关题目:
382. 链表随机节点
384. 打乱数组
398. 随机数索引

文章详解:
游戏中的随机抽样算法

python 复制代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
        
class RandListNode:
    """
    382. 链表随机节点
    https://leetcode.cn/problems/linked-list-random-node/
    """
    def __init__(self, head: ListNode):
        self.head = head
        self.r = random.Random()

    def getRandom(self) -> int:
        i, res = 0, 0
        p = self.head
        # while 循环遍历链表
        while p:
            i += 1
            # 生成一个 [0, i) 之间的整数
            # 这个整数等于 0 的概率就是 1/i
            if 0 == self.r.randint(0, i-1):
                res = p.val
            p = p.next
        return res


class ShuffleArray:
    """
    384. 打乱数组
    https://leetcode.cn/problems/shuffle-an-array/
    """
    def __init__(self, nums: List[int]):
        self.nums = nums

    def reset(self) -> List[int]:
        return self.nums

    def shuffle(self) -> List[int]:
        copy = self.nums.copy()
        n = len(self.nums)
        for i in range(n):
            # 生成一个 [i, n-1] 区间内的随机数
            r = i + random.randint(0, n-i-1)
            # 交换 nums[i] 和 nums[r]
            copy[i], copy[r] = copy[r], copy[i]
        return copy


class RandomIndex:
    """
    398. 随机数索引
    https://leetcode.cn/problems/random-pick-index/description/
    """
    def __init__(self, nums: List[int]):
        self.nums = nums
        # self.rand = random.Random()

    def pick(self, target: int) -> int:
        count, res = 0, -1
        for i in range(len(self.nums)):
            if self.nums[i] != target:
                continue
            count += 1
            if random.randint(1, count) == 1:
                res = i
        return res

from collections import defaultdict
from random import choice
class RandomIndex2:
    """
    398. 随机数索引
    """
    def __init__(self, nums: List[int]):
        self.pos = defaultdict(list)
        for i, num in enumerate(nums):
            self.pos[num].append(i)

    def pick(self, target: int) -> int:
        return choice(self.pos[target])
相关推荐
foundbug99938 分钟前
Polar Code 编解码 MATLAB 实现
开发语言·算法·matlab
李小小钦44 分钟前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
技术不好的崎鸣同学1 小时前
[ACTF2020 新生赛]Include 思路及解法
算法·安全·web安全
先吃饱再说1 小时前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
德迅--文琪1 小时前
游戏运营生命线:服务器选型标准与 DDoS 防护的核心价值
服务器·游戏·ddos
Robot_Nav2 小时前
贪心算法、动态规划与 MPPI 算法结构相关力扣题目汇总
算法·贪心算法·动态规划
战族狼魂2 小时前
每日一课:算法系统学习路线
人工智能·算法·大模型·大语言模型
变量未定义~2 小时前
连通块中点的数量、堆箱子(4星)
算法
j7~3 小时前
【算法】专题二:滑动窗口之水果成蓝,找到字符串中所有字⺟异位词等算法题
c++·算法·滑动窗口·水果成蓝·最小字串覆盖·优选算法精选
木木子223 小时前
# 星座配对深度解析:Select 长列表选择器、矩阵评分算法与数据驱动建议
java·算法·华为·矩阵·harmonyos