array frequency find in c++
xxxxxxxxxx
#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;
}
xxxxxxxxxx
// CPP program to answer queries for frequencies
// in O(1) time.
#include <bits/stdc++.h>
using namespace std;
unordered_map<int, int> hm;
void countFreq(int a[], int n)
{
// Insert elements and their
// frequencies in hash map.
for (int i=0; i<n; i++)
hm[a[i]]++;
}
// Return frequency of x (Assumes that
// countFreq() is called before)
int query(int x)
{
return hm[x];
}
// Driver program
int main()
{
int a[] = {1, 3, 2, 4, 2, 1};
int n = sizeof(a)/sizeof(a[0]);
countFreq(a, n);
cout << query(2) << endl;
cout << query(3) << endl;
cout << query(5) << endl;
return 0;
}