fork download
  1. // Java program to answer
  2. // queries for frequencies
  3. // in O(1) time.
  4.  
  5. import java.io.*;
  6. import java.util.*;
  7.  
  8. class GFG {
  9.  
  10. static HashMap <Integer, Integer> hm = new HashMap<Integer, Integer>();
  11.  
  12. static void countFreq(int a[], int n)
  13. {
  14. // Insert elements and their
  15. // frequencies in hash map.
  16. for (int i=0; i<n; i++)
  17. if (hm.containsKey(a[i]) )
  18. hm.put(a[i], hm.get(a[i]) + 1);
  19. else hm.put(a[i] , 1);
  20. }
  21.  
  22. // Return frequency of x (Assumes that
  23. // countFreq() is called before)
  24. static int query(int x)
  25. {
  26. if (hm.containsKey(x))
  27. return hm.get(x);
  28. return 0;
  29. }
  30.  
  31. // Driver program
  32. public static void main (String[] args) {
  33. int a[] = {1, 3, 2, 4, 2, 1};
  34. int n = a.length;
  35. countFreq(a, n);
  36. System.out.println(query(2));
  37. System.out.println(query(3));
  38. System.out.println(query(5));
  39. }
  40. }
  41.  
Success #stdin #stdout 0.07s 52540KB
stdin
Standard input is empty
stdout
2
1
0