[ISSUE] Majority Vote

Source: Internet
Author: User

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:

    1. If c=0, P saves no word;

    2. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.