在 C++ 中統計陣列中滿足以下條件的配對數量:一個元素的頻率至少是另一個元素的值


給定一個正整數陣列。目標是找到 arr[] 元素對的數量,這些對的元素 (A, B) 滿足 A 的頻率是 B 的倍數,B 的頻率是 A 的倍數。

讓我們透過示例來理解。

輸入 − int arr[] = { 3, 3, 3, 5, 5, 6, 6}

輸出 − 陣列中滿足一個元素的頻率至少是另一個元素的值的配對數量為 1

解釋 − 陣列中 A 出現 B 次且 B 出現 A 次的有效配對是 (3, 3),因為 3 在陣列中出現了 3 次。因此,只有一個有效配對,所以計數為 1。

輸入 − int arr[] = { 3, 3, 3, 3, 3, 5, 5, 5, 6, 6}

輸出 − 陣列中滿足一個元素的頻率至少是另一個元素的值的配對數量為 1

解釋 − 陣列中 A 出現 B 次且 B 出現 A 次的有效配對是 (3, 3)、(5, 5) 和 (3, 5),因為 3 在陣列中出現了 5 次,而 5 在陣列中出現了 3 次。因此,有三個有效配對,所以計數為 3。

下面程式中使用的方案如下

在這個方案中,我們首先建立一個無序對映,其中包含陣列元素的頻率。使用 for 迴圈遍歷無序對映。對於每個元素及其頻率,如果發現任何頻率更多,則增加配對計數。

  • 取一個整數陣列 arr[]。

  • 函式 frequency_other_value(int arr[], int size) 獲取陣列及其大小,並返回滿足以下條件的配對數量:配對是 (A,B),其中 A 至少出現 B 次,反之亦然。

  • 將初始計數設定為 0。

  • 取 unordered_map<int, int> um 用於儲存 arr[] 的元素及其頻率。

  • 使用 for 迴圈遍歷對映,對於每對的第一個值 start=it.second;(it=迭代器),使用 for 迴圈遍歷頻率 >= start 的對映。

  • 為這些配對增加計數。

  • 返回計數作為結果。

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
int frequency_other_value(int arr[], int len){
   int count = 0;
   unordered_map<int, int> um;
   for (int i = 0; i < len; ++i){
      um[arr[i]]++;
   }
   for (auto it : um){
      int start = it.first;
      int end = it.second;
      for (int j = 1; j <= end; j++){
         if (um[j] >= start){
            count++;
         }
      }
   }
   return count;
}
int main(){
   int arr[] = { 3, 3, 3, 5, 5, 6, 6};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Count of pairs in an array such that frequency of one is at least value of other are: "<<frequency_other_value(arr, size);
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

Count of pairs in an array such that frequency of one is at least value of other are: 1

更新於: 2020-12-02

251 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.