使用 C++ 查找数组中唯一对的数量
我们需要适当的知识来在 C++ 中创建数组语法中的多个唯一对。在查找唯一对的数量时,我们计算给定数组中所有唯一对的数量,即可以形成所有可能的对,其中每对都应该是唯一的。例如:
Input : array[ ] = { 5, 5, 9 }
Output : 4
Explanation : The number of all unique pairs are (5, 5), (5, 9), (9, 5) and (9, 9).
Input : array[ ] = { 5, 4, 3, 2, 2 }
Output : 16寻找解决方案的方法
此解决方案有两种方法,它们是:
暴力法
在这种方法中,我们将遍历每个可能的对,将这些对添加到集合中,最后找出集合的大小。这种方法的时间复杂度为 O(n² log n)。
示例
#include <bits/stdc++.h>
using namespace std;
int main () {
int arr[] = { 5, 4, 3, 2, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
// declaring set to store pairs.
set < pair < int, int >>set_of_pairs;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
set_of_pairs.insert (make_pair (arr[i], arr[j]));
int result = set_of_pairs.size();
cout <<"Number of unique pairs : " << result;
return 0;
}输出
Number of unique pairs : 16
以上代码的解释
在此代码中,首先,我们声明一个集合变量,然后,使用两个循环,我们遍历每个可能的对,并使用 i 和 j 将每个对插入到集合中。然后我们计算集合的大小并打印结果。
高效方法
另一种方法是首先找出数组中唯一数字的数量;现在,每个其他唯一元素(包括自身)都可以与任何其他唯一元素构成一对,因此唯一对的数量等于所有唯一数字数量的平方。这种方法的时间复杂度为 O(n)。
示例
#include <bits/stdc++.h>
using namespace std;
int main () {
int arr[] = { 5, 4, 3, 2, 2 };
int n = sizeof (arr) / sizeof (arr[0]);
// declaring set to store unique elements.
unordered_set < int >set_of_elements;
// inserting elements in the set.
for (int i = 0; i < n; i++)
set_of_elements.insert (arr[i]);
int size = set_of_elements.size ();
// finding number of unique pairs
int result = size * size;
cout << "Number of unique pairs in an array: " << result;
return 0;
}输出
Number of unique pairs : 16
以上代码的解释
在此代码中,我们声明一个集合,然后遍历数组的每个元素,将每个元素插入到集合中。之后,我们计算集合的大小,并根据公式 n² 找到结果,并打印输出。
结论
在本文中,我们解决了查找数组中唯一对数量的问题,其中我们讨论了两种解决问题的方法,即简单方法和高效方法。在简单的方法中,我们将所有可能的对插入到一个集合中,时间复杂度为 O(n² log n),而在高效的方法中,我们找到所有唯一数字并使用 n² 找到结果。我们可以在其他语言(如 C、Java、Python 和其他语言)中编写相同的程序。希望本文对您有所帮助。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP