在数组中查找3个或更多重复项

Finding 3 or more duplicates in array

本文关键字:数组 查找 3个      更新时间:2023-10-16

我需要写一个程序来检查数组中是否有3个或更多匹配的数字。我的代码运行良好,直到出现类似"2 2 3 3 5 5 4 1 1"的数组,然后它批准数组中有3个或更多重复项,这是不正确的。也许有人知道一个简单的解决方案对我有帮助?还是我需要重写我的代码?这是我的代码:

#include <iostream>
using namespace std;
void funk(int n, int a[], int &kiek);
int main()
{
int n, a[101],kiek=0;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> a[i];
}
funk(n, a, kiek);
if (kiek > 2) {
cout << "TAIP";
}
else
cout << "NE";
}
void funk(int n, int a[], int &kiek)//funkcijos kūnas
{
int j;
for (int i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (a[i] == a[j])
kiek++;
cout << kiek;
}
}
}

这是输入:

10
2 2 3 3 5 5 4 4 1 1

这是我需要得到的输出:

NE

您的代码存在的问题是:

您正在比较任意2个数字,并且从未重置计数器。因此,如果有一个11,你就增加了计数器。如果有2,那么你也在增加计数器。对于最后的3/3,你也增加了相同的计数器。然后是3。尽管只有两个相同的值。这是行不通的。你能做的就是

  • 读取所有值
  • 计算EACH不同值的频率
  • 检查值的频率
  • 如果任何计数大于2,则显示相应的消息
  • 显示每个值的计数

我会给你看";更现代的";C++方法,并将对下面的示例解决方案使用C++算法。

首先,我们将从用户那里获得要使用的值的数量。我们将把这些值存储在std::vector中。并且,我们使用std::copy_n将值从std::cin复制到我们的std::vector。为此,我们将使用std::istream_iterator,它将迭代用户给定的元素。因此,我们使用一个简单的一行代码来读取用户的所有值。

接下来是频率计数。为此,我们有一个C++中的标准解决方案。你会在网上的几十个地方找到它。我们将使用std::map。键是我们读取到向量中的整数,值是计数器。使用std::map的索引运算符[],如果映射还不存在,我们将向映射添加一个值。使用++,我们只需进行计数,无论该值是已经在std::map中还是刚刚添加。这也是一个非常简单的一行。

然后,我们检查是否有任何计数大于2。为此,我们将使用具有非常简单lambda的STL算法std::any_of。这样,我们就可以创造出您想要的结果。

最后,但同样重要的是,如果计数大于2,我们将显示所有值及其计数。我们用一个超简单的基于范围的循环来实现这一点。我们使用结构化绑定从计数器std::map中提取值。

请参阅:


#include <iostream>
#include <map>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
// Give instructions
std::cout << "How many values do you want do read? Please specify: ";
// Read the number of values to enter
size_t numberOfValues{ 0U }; std::cin >> numberOfValues;

// Read the given number of values from std::cin
std::vector <int> values(numberOfValues);
std::copy_n(std::istream_iterator<int>(std::cin), numberOfValues, values.begin());
// Count each value
std::map<int, size_t> counter{};
std::for_each(values.begin(), values.end(), [&counter](const int& i) { counter[i]++; });
// Check, if any count is bigger than 2
if (std::any_of(counter.begin(), counter.end(), [](const std::pair<int, size_t> & c) { return c.second > 2; }))
std::cout << "TAIPn";
else
std::cout << "NEn";

// Look, if there is any number with a count bigger than 2 and show the result
for (const auto& [value, count] : counter)
if (count > 2) std::cout << value << " --> " << count << "n";
return 0;
}

我希望这能给你一个如何做到这一点的想法。