Posted on

Description

Submission

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int candidate = -1;
        int count = 0;
        
        for(int i = 0; i < nums.size(); ++i) {
            if(nums[i] == candidate) {
                count++;
            } else if(--count < 0) {
                candidate = nums[i];
                count = 1;
            }
        }
        return candidate;
    }
};

Reference

  1. https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm

Leave a Reply

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