Majority Element

来源:互联网 发布:少女大召唤知轩藏书 编辑:程序博客网 时间:2024/03/29 23:32

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;    }};

0 0