在 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

更新於:17-Jan-2020

116 次瀏覽

開始你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.