数组中最大的非重复元素

biggest non-repetitive element in array

本文关键字:元素 数组      更新时间:2023-10-16

所以我需要编写一个程序来计算给定数组中最大的非重复元素。目前我写了一个程序来计算最大的一个,但我不能写算法来排序新数组中的非重复元素。。我的代码:

#include <iostream>
#include <iomanip>
#include <algorithm>
using namespace std;
int main()
{
int n,a[20],b[20],did=0;
cin >> n;
for(int i=0;i<n;i++)
{
cin >> a[i]; // reading input 
}
for(int i=0;i<n;i++) // biggest
{
did=a[0];
if(did<a[i])
did=a[i];
}
for(int i=0;i<n;i++) // trying to write non repetitive ones in new array
{
for(int j=i+1;j<n;j++)
{
if(a[i]!=a[j])
b[i]=a[j];
}
}
for(int i=0;i<n;i++) // biggest from non-repetitive array
{
if(b[i]>b[i-1] && b[i]>b[i+1] && b[i]==did)
cout << b[i];
}
}

(我假设数组不是空的,&也有非重复的正值(

是这样的吗?

#include <vector>
#include <map>
int main()
{
std::map<int, int> m;
// The "array":
std::vector<int> ar{3, 3, 4, 6, 7, 800, 123, 245, 245, 700, 800, 800};
// Count number of repetitions for each element: 
for (auto el : ar)
m[el]++;
// Extract the biggest that has only one appearance:
int result = 0;
for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {
if (iter->second == 1) {
result = iter->first;
break;
}
}
return result; // 700 in this example
}

如果你坚持使用C数组(你也可以使用std::array(:

std::map<int, int> m;
// The array:
const size_t ARRAY_SIZE = 13;
int ar[ARRAY_SIZE] { 3, 3, 4, 5, 6, 7, 800, 123, 245, 245, 700, 800, 800 };
// Count number of repetitions for each element: 
for (size_t i = 0; i < ARRAY_SIZE; i++)
m[ar[i]]++;
// From here is the same code as in the std::vector use example