c*********n 发帖数: 128 | 1 比如有Set set
现在要在set里随机取一个元素出来, 如何取呢?
目前只想到一个比较笨的办法:
int i = (int) (random() * set.toArray().length);
return ( set.toArray() )[i];
这个方法有没有什么问题? 有更好的方法么? |
s*****e 发帖数: 21415 | 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. |
p***p 发帖数: 559 | 3 and do not forget synchrnoized this method |
s*****e 发帖数: 21415 | 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
|
p***p 发帖数: 559 | 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.
|
p***p 发帖数: 559 | 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..
|
r*****l 发帖数: 2859 | 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]; : 这个方法有没有什么问题? 有更好的方法么?
|
c*********n 发帖数: 128 | 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.
|