배열 A가 있다고 가정하고 해당 배열에서 ab =cd가 되도록 두 쌍 (a, b) 및 (c, d)를 선택해야 합니다. 배열 A =[3, 4, 7, 1, 2, 9, 8]이라고 합시다. 출력 쌍은 (4, 2) 및 (1, 8)입니다. 이 문제를 해결하기 위해 다음 단계를 따릅니다. −
- i :=0 ~ n-1에 대해
- j :=i + 1 ~ n-1, do
- 제품 가져오기 =arr[i] * arr[j]
- 해시 테이블에 제품이 없으면 Hash[product] :=(i, j)
- 해시 테이블에 제품이 있으면 이전 및 현재 요소를 인쇄합니다.
- j :=i + 1 ~ n-1, do
예시
#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)