在 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)
- 如果哈希表中存在乘积,则打印前一个和当前元素。
- 对于 j := i + 1 到 n-1,执行以下操作:
示例
#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)
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP