C++中陣列元素頻率計數


給定一個包含重複值的整數陣列,任務是計算陣列中不同元素的頻率並列印結果。

輸入 − int arr[] = {1, 1, 2, 3, 4, 1, 2, 3}

輸出

frequency of 1 is: 3
frequency of 2 is: 2
frequency of 3 is: 2
Frequency of 4 is: 1

輸入 − int arr[] = {2, 3, 4, 1, 5}

輸出

frequency of 1 is: 1
frequency of 2 is: 1
frequency of 3 is: 1
Frequency of 4 is: 1
Frequency of 5 is: 1

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

這個問題有多種解決方案,這些解決方案在編碼方面或複雜度方面可能更簡單。所以讓我們首先看看編碼方面更簡單的方法

  • 建立一個整數型別的陣列變數

  • 使用size()函式計算陣列的大小。

  • 建立一個布林型陣列,例如,檢查陣列大小

  • 從i=0開始迴圈,直到i小於size

  • 在迴圈內部,設定check[i] = 0

  • 從i=0開始迴圈,直到i小於size

  • 在迴圈內部,檢查IF check[i] = 1 則繼續

  • 宣告變數count並將其初始化為1,這將列印頻率計數

  • 從i+1開始迴圈FOR j,直到size

  • 在迴圈內部,檢查如果arr[i] = arr[j],則將check[j]設定為1並將count加1

  • 列印count的值。

另一種解決方案是:

  • 建立一個整數型別的陣列變數

  • 使用size()函式計算陣列的大小。

  • 建立一個unordered_map型別的變數,例如um

  • 從i=0開始迴圈,直到size

  • 在迴圈內部,設定um[arr[i]]++

  • 從auto x開始另一個迴圈,直到um

  • 在迴圈內部,列印頻率。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int frequency(int arr[], int size){
   bool check[size];
   for(int i=0;i<size;i++){
      check[i] = 0;
   }
   for(int i=0; i<size; i++){
      if(check[i]== 1){
         continue;
      }
      int count = 1;
      for(int j = i+1; j<size; j++){
         if (arr[i] == arr[j]){
            check[j] = 1;
            count++;
         }
      }
      cout<<"frequency of "<<arr[i]<<" is: " << count << endl;
   }
}
int main(){
   int arr[] = {1, 2, 3, 1, 2, 3};
   //calculate the size of an array
   int size = sizeof(arr) / sizeof(arr[0]);
   //call function to calculate the frequency
   frequency(arr, size);
   return 0;
}

輸出

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

frequency of 1 is: 2
frequency of 2 is: 2
frequency of 3 is: 2

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
void frequency(int arr[], int size){
   unordered_map<int, int< um;
   for (int i = 0; i < size; i++){
      um[arr[i]]++;
   }
   for (auto x : um){
      cout<<"frequency of "<<x.first<<" is: "<< x.second<< endl;
   }
}
int main(){
   int arr[] = {1, 2, 3, 1, 2, 3 };
   int size = sizeof(arr) / sizeof(arr[0]);
   frequency(arr, size);
   return 0;
}

輸出

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

frequency of 3 is: 2
frequency of 1 is: 2
frequency of 2 is: 2

更新於:2020年8月31日

16K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.