游戏中的随机抽样算法

相关题目:
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])
相关推荐
京东零售技术11 分钟前
下一代 Lakehouse 智能未来新引擎 | Apache Hudi Meetup亚洲站活动回顾
算法
京东零售技术13 分钟前
NeurIPS 2025 | TANDEM:基于双层优化的数据配比学习方法
后端·算法
zmzb010322 分钟前
C++课后习题训练记录Day42
开发语言·c++·算法
CoovallyAIHub24 分钟前
MAR-YOLOv9:革新农业检测,YOLOv9的“低调”逆袭
深度学习·算法·计算机视觉
da_vinci_x28 分钟前
PS 生成式扩展:从 iPad 到带鱼屏,游戏立绘“全终端”适配流
前端·人工智能·游戏·ui·aigc·技术美术·游戏美术
Mr Lee_30 分钟前
Smali 文件生成dex装箱算法整合
开发语言·python·算法
LDG_AGI36 分钟前
【推荐系统】深度学习训练框架(十三):模型输入——《特征索引》与《特征向量》的边界
人工智能·pytorch·分布式·深度学习·算法·机器学习
CoovallyAIHub37 分钟前
如何让SAM3在医学图像上比专用模型还强?一个轻量Adapter如何让它“秒变”专家?
深度学习·算法·计算机视觉
suoge22343 分钟前
热传导控制方程有限元弱形式推导-有限元编程入门
算法
希望有朝一日能如愿以偿43 分钟前
力扣每日一题:统计梯形的数目
算法·leetcode·职场和发展