Algorithm for finding the number which appears the most in a row - C++


I need a help in making an algorithm for solving one problem: There is a row with numbers which appear different times in the row, and i need to find the number that appears the most and how many times it's in the row, ex:


That would be 1 and it appears 5 times.

The algorithm should be fast (that's my problem). Any ideas ?

1/2/2010 6:36:19 PM

Accepted Answer

You could keep hash table and store a count of every element in that structure, like this

h[1] = 5
h[5] = 1
1/2/2010 4:09:12 PM

What you're looking for is called the mode. You can sort the array, then look for the longest repeating sequence.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow