patternjavaModerate
Number of distinct elements in an array
Viewed 0 times
arraydistinctnumberelements
Problem
This is my solution to find the Number of distinct elements in an array. Is there away fast way to do this? It run-time is O(N).
public int DistinctNumberOfItems( int[] A ) {
if (A.length == 0) return 0;
if(A.length == 1) return 1;
Set set = new TreeSet();
for (int i : A) {
set.add(i);
}
return set.size();
}Solution
Your code was better in Rev 1. I don't know why you changed it. Whenever you can get away without special cases, it's probably better to do so.
This code is a pure function of the input array and nothing else. Therefore, it would probably be better as a static function.
Renaming the function from
As others have said, your algorithm, using
This code is a pure function of the input array and nothing else. Therefore, it would probably be better as a static function.
Renaming the function from
NumberOf… to …Count would make it less verbose. You should also respect Java naming conventions, in which method names start with a lowercase letter. The parameter name A also has unconventional capitalization.As others have said, your algorithm, using
TreeSet, is O(n log n). You would need a HashSet for O(n). When constructing a HashSet, it's a good idea to provide an estimate of the collection size, since a wrong guess would hurt performance.public static int distinctItemCount(int[] array) {
Set set = new HashSet(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}Code Snippets
public static int distinctItemCount(int[] array) {
Set<Integer> set = new HashSet<Integer>(array.length);
for (int i : array) {
set.add(i);
}
return set.size();
}Context
StackExchange Code Review Q#81781, answer score: 10
Revisions (0)
No revisions yet.