Linear Time Voting Algorithm. I don't get it

前端 未结 5 684
南方客
南方客 2020-12-07 20:31

As I was reading this (Find the most common entry in an array), the Boyer and Moore\'s Linear Time Voting Algorithm was suggested.

If you follow the link to the si

5条回答
  •  太阳男子
    2020-12-07 20:58

    When the test case is "AAACCBB", the set has no majority. Because no element occurs more than 3 times since the length of "AAACCBB" is 7.

    Here's the code for "the Boyer and Moore's Linear Time Voting Algorithm":

    int Voting(vector &num) {
            int count = 0;
            int candidate;
    
            for(int i = 0; i < num.size(); ++i) {
                if(count == 0) {
                    candidate = num[i];
                    count = 1;
                }
                else
                    count = (candidate == num[i]) ? ++count : --count;
            }
            return candidate;
        }
    

提交回复
热议问题