我曾尝试使用以下代码来获取数组中出现次数最多的元素。它运行良好,但唯一的问题是当有两个或更多元素具有相同的出现次数并且等于出现次数最多的元素时,它只显示扫描的第一个元素。请帮我解决这个问题。
#include <iostream>
using namespace std;
int main()
{
int i,j,a[5];
int popular = a[0];
int temp=0, tempCount, count=1;
cout << "Enter the elements: " << endl;
for(i=0;i<5;i++)
cin >> a[i];
for (i=0;i<5;i++)
{
tempCount = 0;
temp=a[i];
tempCount++;
for(j=i+1;j<5;j++)
{
if(a[j] == temp)
{
tempCount++;
if(tempCount > count)
{
popular = temp;
count = tempCount;
}
}
}
}
cout << "Most occured element is: " << popular;
}
最佳答案
重复解决方案两次并改变两行。
if (count>max_count)
max_count = count;
和:
if (count==max_count)
cout << a[i] << endl;
解决方案:
int a[5];
for (int i=0;i<5;i++)
cin>>a[i];
int max_count = 0;
for (int i=0;i<5;i++)
{
int count=1;
for (int j=i+1;j<5;j++)
if (a[i]==a[j])
count++;
if (count>max_count)
max_count = count;
}
for (int i=0;i<5;i++)
{
int count=1;
for (int j=i+1;j<5;j++)
if (a[i]==a[j])
count++;
if (count==max_count)
cout << a[i] << endl;
}
关于c++ - 使用 C++ 的数组中出现次数最多的元素?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19210001/