游戏中的随机抽样算法

相关题目:
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])
相关推荐
凌肖战39 分钟前
力扣网编程55题:跳跃游戏之逆向思维
算法·leetcode
88号技师1 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
ゞ 正在缓冲99%…2 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss3 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭3 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8243 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug3 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒3 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
军训猫猫头4 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
success4 小时前
【爆刷力扣-数组】二分查找 及 衍生题型
算法