数组中出现次数超过一半的数字

// 5.4.数组中出现次数超过一半的数字
#include "stdafx.h"
using namespace std;
#include <string>
#include <vector>
#include <map>

class Solution
{
public:

    //建立哈希表法//时间O(n),空间O(n/2)
    int  find(vector<int> vec)
    {
        int iRet=-1;
        map <int,int> hash;
        for (int i = 0; i < vec.size(); i++)
        {
            hash[vec[i]]++;
            // hash表如果是相同的 次数会自动+1
            if (hash[vec[i]] > (vec.size() / 2))
            {
                iRet= vec[i];
            }
        }
        return iRet;

    }

};


int main()
{

    vector<int> aa = { 1, 2, 3, 4, 5 };
    vector<int> bb = { 2, 3, 4, 5, 1 };
    vector<int>dd = { 4, 5, 1, 2, 3 };
    vector<int>cc = { 3, 3, 5, 3, 2 };

    Solution sou;
    sou.find(cc);
}

posted on 2020-04-19 16:03  心中日月007  阅读(94)  评论(0编辑  收藏  举报