c++ - 使用 C++ 的数组中出现次数最多的元素?

标签 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;
}

最佳答案

重复解决方案两次并更改两条线。

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/

相关文章:

javascript - 如何在javascript中收集对象数组

arrays - F#:为什么 Array.createZero 这么快?

c - C中生成随机数的函数

algorithm - 常数和组合的数量

java - jvm如何优化循环代码?

c++ - C++ 中嵌套 for 循环的替代方案是什么?

c++ - 错误 : no matching function for call to 'begin(int*&)' c++

c++ - g++ -m32 在 debian amd64 上找不到 libstdc++

algorithm - 动态更新最短路径

c++ - 使用 clang++ 和 SDL 包含路径