Posted on

Description

Submission

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1, count = 0;

        for(auto x: nums) {
            if(!count) candidate = x;
            if(x == candidate) count++;
            else count--;
        }

        count = 0;
        for(auto x: nums) {
            count += (x == candidate);
        }

        if(count > nums.size() / 2) return candidate;
        return -1;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *