What storage method and data structure are best suited for storing a large set of numbers not exceeding 30000 modulo, to ensure fast search and minimal memory usage?
sobes.tech AI
Answer from AI
To store a large set of numbers in the range from -30000 to 30000 for fast search and minimal memory usage, it is best to use data structures with compact representation and efficient access.
Options:
-
Indexed array: if the numbers are integers and the range is known, a boolean array (bitset) of length 60001 (from -30000 to 30000) can be used, where each bit indicates the presence of a number. Search will be O(1), memory — about 7.5 KB (60001 bits).
-
Sorted array with binary search: store numbers in a sorted array and search via binary search in O(log n). Memory is minimal, but search is slightly slower.
-
HashSet or TreeSet: in Java, you can use HashSet<Integer> for quick search (O(1) on average), but with overhead for storing objects and hash table.
Example of using BitSet in Java:
import java.util.BitSet;
public class NumberSet {
private static final int OFFSET = 30000;
private BitSet bitSet = new BitSet(60001);
public void add(int number) {
bitSet.set(number + OFFSET);
}
public boolean contains(int number) {
return bitSet.get(number + OFFSET);
}
}
This approach ensures minimal memory usage and very fast search.