Find the frequency of each array element.
Example 1:
Input: a ={ 1, 3, 5, 1, 2, 7, 2, 1 } Output: Value 1 Freq 3 Value 2 Freq 2 Value 3 Freq 1 Value 5 Freq 1 Value 7 Freq 1
Approach
Java
import java.util.HashMap;
public class FindFrequency {
public static void main(String[] args) {
int a[] = { 1, 3, 5, 1, 2, 7, 2, 1 };
HashMap<Integer, Integer> freq = findFrequency(a);
for (Integer key : freq.keySet()) {
System.out.println("Value " + key + " Freq " + freq.get(key));
}
}
// method to calculate freq of array element
private static HashMap<Integer, Integer> findFrequency(int[] a) {
HashMap<Integer, Integer> freq = new HashMap<>();
// iterate till end of loop
for (int i = 0; i < a.length; i++) {
// add and update frequency
freq.put(a[i], freq.getOrDefault(a[i], 0) + 1);
}
return freq;
}
}
C++
#include <bits/stdc++.h>
using namespace std;
//function to calculate freq of array element
map<int, int> findFrequency(int arr[],int n)
{
map<int,int> freq;
// iterate till end of loop
for (int i = 0; i <n; i++) {
// add and update frequency
freq[arr[i]]++;
}
return freq;
}
int main()
{
int arr[] = { 1, 3, 5, 1, 2, 7, 2, 1 };
int n=sizeof(arr)/sizeof(arr[0]);
map<int, int> freq = findFrequency(arr,n);
for(auto it=freq.begin();it!=freq.end();it++)
cout<<"Value "<<it->first<<" Freq "<<it->second<<"\n";
return 0;
}
No comments:
Post a Comment