✔ 最佳答案
The most efficient way is to use Hashtable.
The way you can go through all elements in the array at most ONCE.
You can view Hashtable as another kind of array where it is great for locating value with a key.
HT[key1] = value1;
HT[key2] = value2;
etc...
Back to your question, suppose we have a hashtable for the element in the array, and the value of the element is the occurrences of such element in the array.
So in the end, your hashtable looks like this:
HT[element1] = 10
HT[element2] = 5
HT[element3] = 1
HT[element4] = 30
HT[element5] = 21
...
MAX ELEMENT = element5
MAX OCCURRENCE = 30
Psuedo-code:
Introduce a variable to keep track of the MAX ELEMENT with the MAX OCCURRENCE
For each element in the array, do
if (ELEMENT exists in the Hashtable)
increment the OCCURRENCE for the element;
if MAX OCCURRENCE < OCCURRENCE
set MAX OCCURRENCE = OCCURRENCE and MAX ELEMENT to the ELEMENT
else (insert the ELEMENT into the array with count of 1)
So by going through the array ONCE you have the ELEMENT with the max "mode".
This is a popular interview question in CS.
Hashtable is good for lookups with the given key very efficiently.
Many languages have that built-in (e.g. PERL, C++ - called map/hash-map).
2007-03-05 07:30:29 補充:
Sorting will work less efficiently.You have to 1) sort, 2) revisit the sorted array and do a countn = array size1) Fastest sort available is n*log(n)2) revisit takes nEfficiency = (n + 1)log(n), it is worse than n (as if you're using HT)Hope it helps!