Any comparison-based sorting will incur O(N log N)
or worse time complexity, so (asymptotically) these are not good advices.
Your approach has O(N)
time complexity, and that's the best you can get. You can try to lower the constant (currently you're making roughly 6*N
accesses to elements of the list).
I would do it in two iterations like this: first count the frequencies using a HashMap. Next, iterate over the entries in the map and keep an ordered 5-element array of the 5 most frequent values seen so far. With each new element, check whether the value is more common than the 5th most common so far, and update the "Top 5" if necessary.
UPDATE A simpler solution, of the same time complexity. First, calculate frequencies using HashMap
. Next, put all the entries into a PriorityQueue
and pop five values. The entries should be value-frequency pairs, comparable by frequency (as in @Jigar's solution). Such an ordering will not be "consistent with equals" (see Comparable for explanation), but that's OK.