使用 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 和其他語言)中編寫相同的程式。希望本文對您有所幫助。

更新於:2021年11月25日

1K+ 次瀏覽

開啟您的職業生涯

完成課程後獲得認證

開始學習
廣告