fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4. public static void main(String[] args) {
  5. int n = 9;
  6. int[] a = {1,3,3,4,1,4,4,4,4}; // array
  7. HashMap<Integer,Integer> b = new HashMap<>(); // hashmap
  8. int i = 0;
  9. while(i<n)
  10. {
  11. int x = a[i];
  12. b.put(x, b.getOrDefault(x, 0) + 1);
  13. i++;
  14. }
  15. //Above for loop took O(n) time.
  16. //All frequencies have been calculated in advance by now.. :-) :-)
  17.  
  18. int[] queries = {3,4,1};
  19. int q = 3;
  20. int j = 0;
  21. while(j<q)
  22. {
  23. int x = queries[j];
  24. System.out.print(b.getOrDefault(x, 0) + " "); //takes O(1) time..
  25. j++;
  26. }
  27. //Above for loop took O(q) time.
  28.  
  29. //Hence total time : O(n+q).
  30. }
  31. }
  32.  
Success #stdin #stdout 0.12s 50428KB
stdin
Standard input is empty
stdout
2 5 2