I am currently using a HashMap
to correspond the duplicate values and the number of times they are repeated. Its linear efficiency O(n)
but I was looking for some built-in methods or a faster way to calculate the number of duplicates for each value in an array (like O(log n)
)?.
Here is my current shot that works:
String[] array = {"Henry", "Henry", "Henry", "Maxwell", "Maxwell"};
HashMap<String, Integer> duplicates = new HashMap<String, Integer>();
int numberOfDuplicates = 1;
for (int i = 0; i < array.length; i++)
{
if (duplicates.put(array[i], numberOfDuplicates) != null) // Duplicate Key
{
numberOfDuplicates++;
}
else // New Key
{
numberOfDuplicates = 1;
}
duplicates.put(array[i], numberOfDuplicates);
}
// Print out duplicate counts
for (String key : duplicates.keySet()) {
System.out.println(key + " " + duplicates.get(key));
}
What about a faster way/pragmatic way? 10Q.