转载自https://blog.csdn.net/Neo_dot/article/details/80642008
https://blog.csdn.net/u013309870/article/details/69788342
有一个整形数组,长度为n,有一个比较小的数k,求数组中出现次数多于n/k的数字
要求空间复杂度O(k),时间复杂度O(k*n)
思路:每次从数组中删除 K 个不同的数,如果某个数的次数大于 N/K ,这个数最后肯定会剩下来
注意:删除后剩余的数不一定全是次数大于 N/K 的数,例如:{1,2,3} k=2, 删除后数组中还剩余 3,但是 3 的次数为 1 ,因此还要看剩余的数的次数是不是大于 N/K.
下面是数组arr[]={1 ,2 ,3 ,3 ,5 ,2 ,2 ,3 ,3 ,3 ,5 ,6 ,2 ,2 ,2 ,3 , 3}处理的简单过程图:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
vector<int> GetNumUpToNK(vector<int> a,int K)
{
vector<int> res;
int len = a.size();
if (len == 0)
return res;
map<int, int> Ktemp;//待消map K项
for (int i = 0; i < len; ++i)
{
int atemp = a[i];
if (Ktemp.find(atemp) != Ktemp.end())//该数在map中
{
++Ktemp[atemp];
}else //不在就加入map中,并判断map的size是否为K,为K则消除K个不同数,相应计数--
{
Ktemp.insert(make_pair(atemp, 1));
if (Ktemp.size() == K)
{
for (auto iter = Ktemp.begin(); iter != Ktemp.end();)
{
--((*iter).second);
if ((*iter).second == 0)
iter = Ktemp.erase(iter);
else
++iter;
}
}
}
}
//此时Ktemp中的元素为备选元素,继续核实。。。。。。
for (auto it = Ktemp.begin();it!=Ktemp.end();++it)
(*it).second = 0;
for (auto c:a) //使用此方法c为只读
{
if (Ktemp.find(c) != Ktemp.end())
{
++Ktemp[c];
}
}
for (auto b:Ktemp)
{
if (b.second>len/K)
{
res.push_back(b.first);
}
}
return res;
}
int main()
{
vector<int> a = { 7,3,3,7,4,5,4,7,3,4,3,4,7,3,4 };
vector<int> ress = GetNumUpToNK(a, 3);
if (ress.empty())
{
cout << "无符合要求的元素" << endl;
}
else
{
for (auto m : ress)
cout << m << " ";
cout << endl;
}
}