Majority Element

来源:互联网 发布:东方证券炒股软件 编辑:程序博客网 时间:2024/03/29 02:42

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.

if extend the problem to more than⌊ n/k ⌋ times,need a k-1 size array.

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


0 0
原创粉丝点击