Complete Solution provided will produce wrong answer at [ 6, 6, 6, 2, 2, 4, 4, 4, 2, 2 ]


#1

Complete Solution provided will produce wrong answer at [ 6, 6, 6, 2, 2, 4, 4, 4, 2, 2 ]
It will show 4 as answer, instead of 2.

Use something like this instead:

class Solution {
    public:
        int majorityElement(vector<int> &num) {
            int majorityIndex = 0;
            for (int count = 1, i = 1; i < num.size(); i++) {
                num[majorityIndex] == num[i] ? count++ : count--;
                if (count == 0) {
                    majorityIndex = i;
                    count = 1;
                }
            }

            return num[majorityIndex];
        }
};