Latoya
Latoya

Reputation:

Java ( Counting Distinct Integers )

how do you return number of distinct/unique values in an array for example

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

Upvotes: 2

Views: 7185

Answers (4)

Tamas Czinege
Tamas Czinege

Reputation: 121324

Really depends on the numbers of elements in the array. If you're not dealing with a large amount of integers, a HashSet or a binary tree would probably be the best approach. On the other hand, if you have a large array of diverse integers (say, more than a billion) it might make sense to allocate a 2^32 / 2^8 = 512 MByte byte array in which each bit represents the existence or non-existence of an integer and then count the number of set bits in the end.

A binary tree approach would take n * log n time, while an array approach would take n time. Also, a binary tree requires two pointers per node, so your memory usage would be a lot higher as well. Similar consideration apply to hash tables as well.

Of course, if your set is small, then just use the inbuilt HashSet.

Upvotes: 2

dcrosta
dcrosta

Reputation: 26258

A set stores each unique (as defined by .equals()) element in it only once, and you can use this to simplify the problem. Create a Set (I'd use a HashSet), iterate your array, adding each integer to the Set, then return .size() of the Set.

Upvotes: 4

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

An efficient method: Sort the array with Arrays.sort. Write a simple loop to count up adjacent equal values.

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422006

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

Upvotes: 13

Related Questions