繁体   English   中英

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

[英]finding the most repeated elements in an array with length n

  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重复3次。 显然,我给全局常数赋予了10的值,但是对于“ n”(未知)数我该怎么做。 谢谢。

在开始时排序数组

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;

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

  • 对于未知的数组大小(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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM