在 C++ 中打印所有出现次数最多的和对
在该问题中,我们得到一个由 n 个唯一整数组成的数组。我们需要求出数组中两个整数之和,该和出现次数最多。该问题有多个解决方案,你需要找到所有解决方案。
Input : array = { 1, 12, 5, 7, 9, 11}
Output : 16 12说明 − 和 16 和 12 出现两次。
5 + 11 = 16 & 7 + 9 = 16 1 + 11 = 12 & 5 + 7 = 12
现在解决这个问题,我们的方法是检查每个和对的出现次数,然后打印出现次数最多的那对。
解决问题的步骤 −
Step 1: Iterate over all pairs. Step 2: The occurrence of sum pairs is counted using hash-table. Step 3: After the interation process is done, the sum pair with maximum occurrence is printed.
示例
#include <bits/stdc++.h>
using namespace std;
void sumPairs(int a[], int n){
unordered_map<int, int> pairSum;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
pairSum[a[i] + a[j]]++;
}
}
int occur = 0;
for (auto it : pairSum) {
if (it.second > occur) {
occur = it.second;
}
}
for (auto it : pairSum) {
if (it.second == occur)
cout << it.first <<"\t";
}
}
int main(){
int a[] = { 1, 12, 5, 7, 9, 11 };
int n = sizeof(a) / sizeof(a[0]);
cout<<"The sum pairs with max ccurence are : "<<endl;
sumPairs(a, n);
return 0;
}输出
出现次数最多的和对是 −
16 12
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP