Redian新闻
>
要随机返回一个Set的里的元素, 如何操作呢?
avatar
要随机返回一个Set的里的元素, 如何操作呢?# Java - 爪哇娇娃
c*n
1
比如有Set set
现在要在set里随机取一个元素出来, 如何取呢?
目前只想到一个比较笨的办法:
int i = (int) (random() * set.toArray().length);
return ( set.toArray() )[i];
这个方法有没有什么问题? 有更好的方法么?
avatar
s*e
2
i have dealt with this before.
i think an even better way is to keep a linear interface.
use an array to store the items.
use a set to store key-->array_index mappings.
then you can support insert/delete/random_access.
time complexity is the same as the set. just a constant overhead.
avatar
p*p
3
and do not forget synchrnoized this method
avatar
s*e
4
won't work.
check key uniqueness and insert will be O(n)
set + array is the best. hehe..

【在 p***p 的大作中提到】
: and do not forget synchrnoized this method
avatar
p*p
5
use arraylist for random access
for add/remove LinkedList

【在 s*****e 的大作中提到】
: i have dealt with this before.
: i think an even better way is to keep a linear interface.
: use an array to store the items.
: use a set to store key-->array_index mappings.
: then you can support insert/delete/random_access.
: time complexity is the same as the set. just a constant overhead.

avatar
p*p
6
a general question
when is good to use SET?

【在 s*****e 的大作中提到】
: won't work.
: check key uniqueness and insert will be O(n)
: set + array is the best. hehe..

avatar
r*l
7
Why don't you just iterator through the Set
and exit the iteration at the random number?
Keep in mind that toArray() in Set does not
guarantee the order.

【在 c*********n 的大作中提到】
: 比如有Set set
: 现在要在set里随机取一个元素出来, 如何取呢?
: 目前只想到一个比较笨的办法:
: int i = (int) (random() * set.toArray().length);
: return ( set.toArray() )[i];
: 这个方法有没有什么问题? 有更好的方法么?

avatar
c*n
8
en, good idea

Why don't you just iterator through the Set
and exit the iteration at the random number?
Keep in mind that toArray() in Set does not
guarantee the order.

【在 r*****l 的大作中提到】
: Why don't you just iterator through the Set
: and exit the iteration at the random number?
: Keep in mind that toArray() in Set does not
: guarantee the order.

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。