It depends on how big N .
With small N values, you can use the HashSet<Integer> to store numbers that you have already issued. This gives you an O(1) lookup and O(N) space usage.
A BitSet for the range 0-999999 will use approximately 125 Kbytes, regardless of the value of N With sufficiently large N values, this will be more space than a HashSet . I'm not sure if the value is N , where BitSet will use less space, but my guest will be between 10,000 and 20,000.
Can someone tell me if the BitSet memory requirements BitSet number of bits or the number of bits set?
The size is determined either by the largest bit that has ever been set, or by the nBits parameter if you use the BitSet(int nBits) constructor BitSet(int nBits) .
and what is the difficulty of setting / testing bits?
Testing B O(1) bits O(1) .
The setting bit B is the best O(1) and O(B) if you need to expand an array of bit set support. However, since the size of the support array is the next highest power of 2, the cost of expansion can usually be amortized over several BitSet operations.
source share