c++ - 数组中最大的非重复元素
问题描述
所以我需要编写程序来计算给定数组中最大的非重复元素。目前我编写程序来计算最大的一个,但我不能编写算法来对新数组中的非重复元素进行排序.. 我的代码:
#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
推荐阅读
- laravel - Laravel Spark Next 挂起等待订阅
- django - 当我运行收集静态命令时,Django 没有在浏览器中更新静态 css 文件设计
- python-3.x - python使用'del'从列表中删除一个元素
- api - 在没有 MVC 项目的情况下使用 Xero OAuth2 .Net SDK
- python - Kivy - 尝试使用 my.kv 文件时出错
- javascript - Javascript 和 HTML:单击提交时不显示验证警报消息
- firebase - 我在 Flutter itemBuilder 中不断收到此错误
- android - 如何在 Android 中保存 agora 流?
- laravel - 如何在 Laravel 8 中计算银行余额和银行总余额?
- java - Intellij 中的 junit 未识别 lombok 注释