How to select a random element in std::set in less than O(n) time?(如何在少于 O(n) 的时间内在 std::set 中选择一个随机元素?)
问题描述
这个问题添加了约束.
我愿意允许不统一的选择,只要不偏向一边.
I'm willing to allow not-uniform selection as long as it's not to lop sided.
鉴于集合通常实现为二叉搜索树",而我期望它们将包含某种用于平衡的深度或大小信息,我希望您可以对树进行某种加权随机游走.但是我不知道有任何远程便携的方式来做到这一点.
Given that "sets are typically implemented as binary search trees" and I expect they will contain some kind of depth or size information for balancing, I would expect you could do some sort of weighted random walk of the tree. However I don't know of any remotely portable way to do that.
约束不适用于摊销时间.
The constraint is NOT for the amortized time.
推荐答案
引入大小等于set的数组.使数组元素保存集合中每个元素的地址.生成以数组/集合大小为界的随机整数R,在R索引的数组元素中选取地址并取消引用以获得集合的元素.
Introduce array with size equal to set. Make array elements hold addresses of every element in set. Generate random integer R bounded by array/set size, pick address in array's element indexed by R and dereference it to obtain set's element.
这篇关于如何在少于 O(n) 的时间内在 std::set 中选择一个随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在少于 O(n) 的时间内在 std::set 中选择一个随机元素?
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
