在长度为n的数组中查找重复次数最多的元素

时间:2016-02-11 20:07:40

标签: c++ arrays

  const int N=10;

  int main()
  {

    int arr[N]={4,4,6,4,6,6,7,9,9,9};

    for (int i = 0; i < N; i++)
        for (int j=i+1; j<N; j++)
        {
            if (arr[i]==arr[j])

              cout << arr[i];
        }


    return 0;
 }

这给出了所有重复的元素(意味着它将给出444,666,999)。我的问题是我希望输出只有4,6,9而不是4重复三次。显然我给了我的全局常量值10但是我怎么能为&#34; n&#34; (未知电话。谢谢。

2 个答案:

答案 0 :(得分:0)

在开始排序数组

sort(arr, arr + n);

然后迭代并找到最重复元素的计数,你可以这样做:

int maxCnt = 0;
int curCnt = 1;
for (int i = 1; i < n; i++) {
 if (arr[i] == arr[i - 1]) curCnt++;
 else 
   {
     maxCnt = max(maxCnt, curCnt);
     curCnt = 1;
   }
}
maxCnt = max(maxCnt, curCnt);

然后再次迭代累积curCnt并且当curCnt == maxCnt输出数

curCnt = 1;
for (int i = 1; i < n; i++) {
 if (curCnt == maxCnt) cout << arr[i - 1] << ' ';
 if (arr[i] == arr[i - 1]) {
   curCnt++;
 }
 else curCnt = 1;
}
if (curCnt == maxCnt) cout << arr[n - 1] << endl;

此解决方案仅输出重复次数最多的数字。

答案 1 :(得分:0)

  • 对于未知数组大小(N),请使用“基于范围的循环”。
  • 使用std::map计算每个元素的计数。

以下是代码:

#include <map>
#include <iostream>

using namespace std;

int main()
{
    const int arr[]{ 4,4,6,4,6,6,7,9,9,9 };

    // Get count for each element.
    map<int, int> elementCount;
    for (const auto& e : arr)
    {
        elementCount[e] += 1;
    }

    // Get the highest count.
    int highestCount = 0;
    for (const auto& e : elementCount)
    {
        cout << e.first << " " << e.second << endl;
        if (e.second > highestCount)
        {
            highestCount = e.second;
        }
    }

    // Get the elements with the hightest count.
    cout << endl << "Elements with the hightest count:" << endl;
    for (const auto& e : elementCount)
    {
        if (e.second == highestCount)
        {
            cout << e.first << " ";
        }
    }
    cout << endl;
    return 0;
}
相关问题