rmp2150 rmp2150 - 1 month ago 16
Java Question

Find number of distinct elements in a linked list

I have a LinkedList that contains many objects. How can I find the number and frequency of the distinct elements in the LinkedList.

Answer

You can iterate the list with a for-each loop while maintaining a histogram.

The histogram will actually be a Map<T,Integer> where T is the type of the elements in the linked list.

If you use a HashMap, this will get you O(n) average case algorithm for it - be sure you override equals() and hashCode() for your T elements. [if T is a built-in class [like Integer or String], you shouldn't be worried about this, they already override these methods].

The idea is simple: iterate the array, for each element: search for it in the histogram - if it is not there, insert it with value 1 [since you just saw it for the first time]. If it is in the histogram already, extract the value, and re-insert the element - with the same key and with value + 1.

should look something like this: [list is of type LinkedList<Integer>]

Map<Integer,Integer> histogram = new HashMap<Integer, Integer>();
for (Integer x : list) {
    Integer value = histogram.get(x);
    if (value == null) histogram.put(x,1);
    else histogram.put(x, value + 1);
}