Java (counting distinguished integers)
Really depends on the number of elements in the array. Unless you are dealing with a lot of integers, a HashSet or binary tree is probably your best bet. On the other hand, if you have a large array of diverse integers (say, over a billion), it might make sense to allocate an array of bytes of size 2 ^ 32/2 ^ 8 = 512 MB, in which each bit represents the existence or non-existence of an integer numbers and then counting the number of bits set at the end.
The binary tree approach will take n * log n times, whereas the array approach will take n times. Also, the binary tree requires two pointers per node, so your memory usage will be much higher. The same consideration applies to hash tables.
Of course, if your set is small, just use the built-in HashSet.
source to share