The source of their own github.io
http://awarrior.github.io/majority-vote/
Describe
Give you a log of searching so contains N words, how to find out one key word which appears over N/2 times (definitely E xists), just using O (n) time complexity?
Analyze
There is a very important pre-condition in this issue: the target word which we want to find definitely exists.
Let's see several examples first:
(A B) C A A B
(A B) C A A B A
It doesn ' t matter if we leave a&b out, A is still the result.
(C B) A A A B A
It doesn ' t matter if we leave c&b out, A is still the result.
(A A) C B A B A
We have to record the apperance times of A for further judgement.
Here we consider the word each time. A majority word is still a major one if we minus both words which are different from each of the other. Otherwise, if the words is the same, we also need to save the information of this word.
Actually, we can consider this words sequence as conbination of several word pairs (both words).
Resolve
We can set the variables to use, one for saving current word (p) and another for counting (c). Initialize c=0 and P points to the front of the first word.
Make a rule and we iterate the words sequence like this:
If c=0, P saves no word;
Else if the next word equals the current one, c+=1; Else C-=1.
You can see the whole process in this website for details:
Http://www.cs.utexas.edu/~moore/best-ideas/mjrty/index.html
PAPER TITLE: mjrty-a Fast Majority Vote algorithm
Code
//Use number expression for exampleintn[Ten] = {2,1,2,3,4,2,2,1,2,2 };intc =0, p; for(inti:n) {if(c = =0) {p=i; ++C; } Else { if(i = =p)++C; Else--C; }}std::cout<< c << std::endl << p << Std::endl;
[ISSUE] Majority Vote