在 C++ 中找出陣列中滿足 ab = cd 的所有對 (a, b) 和 (c, d)


假設我們有一個數組 A,從該陣列中,我們必須選擇兩對 (a, b) 和 (c, d),使得 ab = cd。令陣列 A = [3, 4, 7, 1, 2, 9, 8]。輸出對為 (4, 2) 和 (1, 8)。為了解決這個問題,我們將遵循以下步驟:

  • 對於 i := 0 到 n-1,執行以下操作:
    • 對於 j := i + 1 到 n-1,執行以下操作:
      • 獲取乘積 = arr[i] * arr[j]
      • 如果雜湊表中不存在乘積,則 Hash[product] := (i, j)
      • 如果雜湊表中存在乘積,則列印前一個和當前元素。

示例

 現場演示

#include <iostream>
#include <unordered_map>
using namespace std;
void displayPairs(int arr[], int n) {
   bool found = false;
   unordered_map<int, pair < int, int > > Hash;
   for (int i=0; i<n; i++) {
      for (int j=i+1; j<n; j++) {
         int prod = arr[i]*arr[j];
         if (Hash.find(prod) == Hash.end())
            Hash[prod] = make_pair(i,j);
         else{
            pair<int,int> pp = Hash[prod];
            cout << "(" << arr[pp.first] << ", " << arr[pp.second] << ") and (" << arr[i]<<", "<<arr[j] << ")"<<endl; found = true;
         }
      }
   }
   if (found == false)
   cout << "No pairs have Found" << endl;
}
int main() {
   int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
   int n = sizeof(arr)/sizeof(int);
   displayPairs(arr, n);
}

輸出

(1, 6) and (2, 3)
(1, 8) and (2, 4)
(2, 6) and (3, 4)
(3, 8) and (4, 6)

更新於:2019 年 10 月 24 日

145 次瀏覽

開啟你的職業生涯

完成課程認證

開始
廣告
© . All rights reserved.