Java (counting distinguished integers)

how do you return the number of distinct / unique values ​​in an array like

int[] a = {1,2,2,4,5,5};

      

+2


source to share


4 answers


Set<Integer> s = new HashSet<Integer>();
for (int i : a) s.add(i);
int distinctCount = s.size();

      



+13


source


The set only stores each unique (as defined in it .equals () element) once and you can use it to simplify the problem. Create a set (I would use a HashSet), iterate over your array, add each integer to the Set, and then return .size () to the Set.



+4


source


Effective method: Sort the array with Arrays.sort

. Write a simple loop to count adjacent equal values.

+3


source


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.

+2


source







All Articles