使用c ++在数组中出现的大多数元素?

Aru*_*dey 4 c++ arrays algorithm

我曾尝试过以下代码来获取数组中最常出现的元素.它运行良好但唯一的问题是当有两个或多个元素具有相同的出现次数并且等于最多出现的元素时,它只显示扫描的第一个元素.请帮我解决这个问题.

#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;
}
Run Code Online (Sandbox Code Playgroud)

has*_*san 10

重复两次解决方案,改变两行.

if (count>max_count)
    max_count = count;
Run Code Online (Sandbox Code Playgroud)

有:

if (count==max_count)
    cout << a[i] << endl;
Run Code Online (Sandbox Code Playgroud)

解:

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;
}
Run Code Online (Sandbox Code Playgroud)