【算法】设计并实现一个算法以判断其中是否存在出现次数超过所有元素一半的元素(C++源码)
- 一、设计
- 二、要求:
- 三、设计思路
- 四、源代码
一、设计
设计并实现一个算法以判断其中是否存在出现次数超过所有元素一半的元素(C++源码)
对于给定的一个含n(n>2)个整数的数组,请设计并实现一个算法以判断其中是否存在出现次数超过 所有元素一半的元素,如有请打印输出该元素。
二、要求:
1、请选用合适的STL容器进行算法设计与实现;
2、请通过多组测试数据以验证算法的正确性。
三、设计思路
① 定义vec(),cnt()数组,输入vec()数组;
② 对于数的个数进行累加, 保存于cnt()数组中,判断个数是否大于判断出的最大个数的数字,若满足则保存数字于temp中;
③ 判断max是否>=n/2,若大于则输出Num counts of “temp”" is greater than “n/2”。
四、源代码
#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<ctime>
#include<vector>
using namespace std;
int main()
{
int n,i,j;
int max = 0, temp=0;
cout<<"Please enter array size:";
cin>>n;
vector<int>vec(n);
vector<int>cnt(n, 0);
for(i=0;i<n;i++)
{
cout<<"a["<<i<<"]:";
cin>>vec[i];
}
cout<<endl<<"The array is:"<<endl;
for(i=0;i<n;i++)
{
cout<<vec[i]<<" ";
}
cout << endl;
for(i=0;i<n;i++)
{
cnt[vec[i]]++;
if(cnt[vec[i]] > max)
{
max = cnt[vec[i]];
temp=vec[i];
}
}
if(max>=n/2)
{
cout<<"Num counts of "<<temp<<" is greater than "<<n/2;
}
else
{
cout<<"No element's occurance is grteater than "<<n/2;
}
return 0;
}