找众数

int findMajority(const std::vector<int> &array)
{
        assert(!array.empty ());
        int    majority   = 0;
        size_t counter    = 0;
        std::for_each(array.cbegin (), array.cend (), [&](int i)
        {
                if (counter == 0){
                        majority = i;
                }else{
                        if (majority == i){
                                ++counter;
                        }else{
                                --counter;
                        }
                }
        });
        return majority;
}

 

posted @ 2016-03-07 22:03  wu_overflow  阅读(207)  评论(0编辑  收藏  举报