【算法刷题】找出数组中出现次数大于N/K的所有元素

数组中出现次数超过一半(可实现时间复杂度o(n),空间复杂度o(1))的进阶版

鸽巢原理:出现次数大于N/K的元素的个数至多为(M-1)个

思路:

每次从数组中删除k个不同的元素,直到不能再删了为止。那么最后数组中剩余的元素就是候选元素。

因此  可建立一个k长度的map记录从数组中待消的元素,例如数组a={4,3,3,9,4,2,1,4,3,4,9,2}  N=12,k=3 ,则每次应该删3个数,依次遍历数组:

       |               |             |                                                                                |

       |               |         3  |         3                                                                     |

4     |     4   3    |    4   3  |    4   3   9 (此时map的size为3,删除最后一行439)  |   

直到遍历完数组。。。。map中留下的元素即为备选元素,再返过去统计备选元素出现次数是否真的是大于N/K

时间复杂度o(kN)      空间复杂度o(K)  map的空间  

#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;
	}

	
}

猜你喜欢

转载自blog.csdn.net/neo_dot/article/details/80642008