It depends on how large N
is.
For small values of N
, you could use a HashSet<Integer>
to hold the numbers you have already issued. This gives you O(1)
lookup and O(N)
space usage.
A BitSet
for the range 0-999999 is going to use roughly 125Kb, regardless of the value of N
. For large enough values of N
, this will be more space efficient than a HashSet
. I'm not sure exactly what the value of N
is where a BitSet
will use less space, but my guestimate would be 10,000 to 20,000.
Can someone tell me if the memory requirements of
BitSet
are related to the number of bits or to the number of set bits?
The size is determined either by the largest bit that has ever been set, or the nBits
parameter if you use the BitSet(int nBits)
constructor.
and what is the complexity to setting/testing a bit ?
Testing bit B
is O(1)
.
Setting bit B
is O(1)
best case, and O(B)
if you need to expand the bitset backing array. However, since the size of the backing array is the next largest power of 2, the cost of expansion can typically be amortized over multiple BitSet
operations.