多次出現的陣列元素是?
在此,我們將看到一個問題。我們有一個數組。我們的任務是找出其出現頻率超過 1 的元素。假設元素為 {1、5、2、5、3、1、5、2、7}。此處 1 出現了 2 次,5 出現了 3 次,2 出現了 3 次,其他元素僅出現 1 次。因此,輸出將為 {1、5、2}
演算法
moreFreq(arr, n)
Begin define map with int type key and int type value for each element e in arr, do increase map.key(arr).value done for each key check whether the value is more than 1, then print the key End
示例
#include <iostream> #include <map> using namespace std; void moreFreq(int arr[], int n){ map<int, int> freq_map; for(int i = 0; i<n; i++){ freq_map[arr[i]]++; //increase the frequency } for (auto it = freq_map.begin(); it != freq_map.end(); it++) { if (it->second > 1) cout << it->first << " "; } } int main() { int arr[] = {1, 5, 2, 5, 3, 1, 5, 2, 7}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Frequency more than one: "; moreFreq(arr, n); }
輸出
Frequency more than one: 1 2 5
廣告