问题
Possible Duplicate:
Finding the max repeated element in an array
If there is a word stream, with one word having an occurrence rate of 51% or more, how can we find the most frequent word if only string, and an int can be stored in the memory at a time to help us find it.
We can only access each word a single time, since this is a stream.
No specific language is necessary, but this is mainly intended with Java in mind.
Also I'm not asking for code, just the idea. :)
回答1:
For completeness, implementation in Java of the algorithm presented in the duplicate I pointed at, applied to an example:
public static void main(String[] args) throws InterruptedException {
List<String> list = Arrays.asList("a", "b", "c", "a", "d", "e", "a", "a", "b", "b", "a");
int counter = 0;
String mostFrequentWord = "";
for (String streamed : list) {
if (streamed.equals(mostFrequentWord)) {
counter++;
} else if (counter == 0) {
mostFrequentWord = streamed;
counter = 1;
} else {
counter--;
}
}
System.out.println(mostFrequentWord);
}
来源:https://stackoverflow.com/questions/11547686/how-to-find-the-most-frequent-word-in-a-word-stream