游戏中的随机抽样算法

相关题目:
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])
相关推荐
NAGNIP6 分钟前
Kimi Linear——有望替代全注意力的全新注意力架构
算法·面试
智驱力人工智能21 分钟前
无人机河道漂浮物检测 从项目构建到价值闭环的系统工程 无人机河道垃圾识别 农村河道漂浮物智能清理方案 无人机辅助河道清洁预警
opencv·算法·安全·yolo·目标检测·无人机·边缘计算
Yeniden22 分钟前
Deepeek用大白话讲解 --> 备忘录模式(企业级场景1,撤销重做2,状态保存3,游戏存档4)
游戏·备忘录模式
德福危险29 分钟前
C语言数据类型与变量 系统总结笔记
c语言·笔记·算法
@淡 定30 分钟前
JVM调优参数配置详解
java·jvm·算法
CoovallyAIHub37 分钟前
从电影特效到体育科学,运动追踪只能靠“人眼”吗?
深度学习·算法·计算机视觉
风筝在晴天搁浅38 分钟前
hot100 48.旋转图像
算法
TechNomad1 小时前
排序算法:希尔排序算法
数据结构·算法·排序算法
热爱生活的猴子1 小时前
算法中DFS & BFS 核心学习笔记
算法·深度优先·宽度优先
im_AMBER1 小时前
Leetcode 83 使数组平衡的最少移除数目中等相关标签 | 尽可能使字符串相等
数据结构·c++·笔记·学习·算法·leetcode