在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,执行
得到乘积=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)
热门推荐
10 老师圣诞贺卡祝福语简短
11 赞美老师祝福语英文简短
12 朋友入伙搬家祝福语简短
13 2026年春节祝福语简短
14 创业失败返乡祝福语简短
15 横幅家庭生日祝福语简短
16 新年过后奋斗祝福语简短
17 学生开心成语祝福语简短
18 单位搬迁新楼祝福语简短