如何在小于O(n)的时间内在std :: set中选择一个随机元素? [英] How to select a random element in std::set in less than O(n) time?

查看:902
本文介绍了如何在小于O(n)的时间内在std :: set中选择一个随机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题带有附加的约束。 p>

我愿意允许不均匀的选择,只要不要偏侧。



由于集合通常实现为二叉搜索树,我希望他们将包含某种深度或大小信息进行平衡,我希望你可以做一些加权随机游走的树。然而,我不知道任何远程可移植的方式来做。



编辑:约束不是为摊销时间。

解决方案

介绍尺寸等于set的数组。使数组元素保存集合中每个元素的地址。生成由数组/集合大小限定的随机整数 R ,在由 R 索引的数组元素中选择地址并取消引用set的元素。


This question with an added constraint.

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.

Edit: The constraint is NOT for the amortized time.

解决方案

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中选择一个随机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆