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


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

    天天向上
  • 相关阅读:
    美国州名来源
    SQL Constraint/Index
    英语中的 姓氏/Surname
    GNU glibc
    英语人名探源/字母升序排列
    About 'atoi'
    封装一个类似jquery的ajax方法
    函数柯里化
    AngularJS实现TodoMVC
    webpack简单使用
  • 原文地址:https://www.cnblogs.com/hg07/p/12731929.html
Copyright © 2020-2023  润新知