Majority Element

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.


class Solution {
public:
    int majorityElement(vector<int> &num)
    {
        int len = num.size();
        int tmp=num[0], nb=1;
        for(int i=1;i<len;i++)
        {
            if(num[i]!=tmp)
                nb--;
            else
                nb++;
            if(nb==0)
            {
                tmp = num[i];
                nb = 1;
            }
        }
        return tmp;
    }
};

你可能感兴趣的:(Majority Element)