[英]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;
此解決方案將只輸出最多重復的數字一次。
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.