当前位置: 首页 > news >正文

游戏中的随机抽样算法

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

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

class ListNode:def __init__(self, val=0, next=None):self.val = valself.next = nextclass RandListNode:"""382. 链表随机节点https://leetcode.cn/problems/linked-list-random-node/"""def __init__(self, head: ListNode):self.head = headself.r = random.Random()def getRandom(self) -> int:i, res = 0, 0p = self.head# while 循环遍历链表while p:i += 1# 生成一个 [0, i) 之间的整数# 这个整数等于 0 的概率就是 1/iif 0 == self.r.randint(0, i-1):res = p.valp = p.nextreturn resclass ShuffleArray:"""384. 打乱数组https://leetcode.cn/problems/shuffle-an-array/"""def __init__(self, nums: List[int]):self.nums = numsdef reset(self) -> List[int]:return self.numsdef 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 copyclass 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, -1for i in range(len(self.nums)):if self.nums[i] != target:continuecount += 1if random.randint(1, count) == 1:res = ireturn resfrom 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])
http://www.lryc.cn/news/219537.html

相关文章:

  • 【Qt之QtXlsx模块】安装及使用
  • 如何在 TFRecord 文件上训练 Keras 模型实现黑色素瘤分类器
  • C++ 复制控制之复制构造函数
  • Windows ObjectType Hook 之 ParseProcedure
  • 下载树莓派对应的64位Ubuntu系统步骤
  • 网络运维Day03
  • LangChain+LLM实战---ChatGPT的工作原理
  • Appium知多少
  • 【实战Flask API项目指南】之五 RESTful API设计
  • 尚硅谷大数据项目《在线教育之实时数仓》笔记005
  • 算法通过村第十八关-回溯|青铜笔记|什么叫回溯(中篇)
  • generate by chatgpt:应用上线前的checkList(部分是我自己的回答)
  • Redis实战 | 使用Redis 的有序集合(Sorted Set)实现排行榜功能,和Spring Boot集成
  • 基于信号功率谱特征和GRNN广义回归神经网络的信号调制类型识别算法matlab仿真
  • matplotlib从起点出发(10)_Tutorial_10_Layout
  • HTTP头部信息解释分析(详细整理)(转载)
  • 集线器、交换机、网桥、路由器、网关
  • 项目实战:新增@Controller和@Service@Repository@Autowire四个注解
  • 校验 ChatGPT 4.0 真实性的三个经典问题:快速区分 GPT3.5 与 GPT4,并提供免费测试网站
  • Jetpack:030-Jetpack中的状态
  • AD教程 (七)元件的放置
  • ubuntu22.04为什么鼠标会自动丢失焦点
  • FastBond2阶段2——基于ESP32C3开发的简易IO调试设备
  • 03、SpringBoot + 微信支付 ---- 创建订单、保存二维码url、显示订单列表
  • 【echarts基础】在柱形图上设置文本
  • 小户型工业风,陌生上开花知书香。福州中宅装饰,福州装修
  • Gorm 中的迁移指南
  • 基于.NET、Uni-App开发支持多平台的小程序商城系统 - CoreShop
  • [python] 在多线程中将`logging.info`输出到不同的文件中 (生产者消费者)
  • MySQL进阶_5.逻辑架构和SQL执行流程