fork(1) download
  1. import java.util.*;
  2. class Foo{
  3. Map<Integer,Integer> map1;
  4. Map<Integer,Set<Integer>> map2;
  5. int max_freq;
  6. Foo(){
  7. map1 = new HashMap<>();
  8. map2 = new HashMap<>();
  9. map2.put(0,new HashSet<>());
  10. max_freq = 0;
  11. }
  12.  
  13.  
  14. public void add(int x){
  15. map1.putIfAbsent(x,0);
  16. int curr_f = map1.get(x);
  17. if(!map2.containsKey(curr_f)){
  18. map1.put(x,1);
  19. }else{
  20. map1.merge(x,1,Integer::sum);
  21. }
  22.  
  23. map2.putIfAbsent(map1.get(x),new HashSet<>());
  24. map2.get(map1.get(x)-1).remove(x); // remove from previous frequency list
  25. map2.get(map1.get(x)).add(x);// add to current frequency list
  26. max_freq = Math.max(max_freq,map1.get(x));
  27. printState();
  28. }
  29.  
  30. public List<Integer> delete(){
  31. List<Integer> ls = new ArrayList<>(map2.get(max_freq));
  32. map2.remove(max_freq);
  33. max_freq--;
  34. while(max_freq > 0 && map2.get(max_freq).size() == 0) max_freq--;
  35. printState();
  36. return ls;
  37. }
  38.  
  39. public void printState(){
  40. System.out.println(map1.toString());
  41. System.out.println("Maximum frequency: " + max_freq);
  42. for(Map.Entry<Integer,Set<Integer>> m : map2.entrySet()){
  43. System.out.println(m.getKey() + " " + m.getValue().toString());
  44. }
  45. System.out.println("----------------------------------------------------");
  46. }
  47.  
  48. }
  49. class Ideone{
  50. public static void main(String[] args) {
  51. Foo f = new Foo();
  52. f.add(1);
  53. f.add(2);
  54. f.add(2);
  55. f.add(2);
  56. f.delete();
  57. f.delete();
  58. }
  59. }
  60.  
Success #stdin #stdout 0.12s 36560KB
stdin
Standard input is empty
stdout
{1=1}
Maximum frequency: 1
0 []
1 [1]
----------------------------------------------------
{1=1, 2=1}
Maximum frequency: 1
0 []
1 [1, 2]
----------------------------------------------------
{1=1, 2=2}
Maximum frequency: 2
0 []
1 [1]
2 [2]
----------------------------------------------------
{1=1, 2=3}
Maximum frequency: 3
0 []
1 [1]
2 []
3 [2]
----------------------------------------------------
{1=1, 2=3}
Maximum frequency: 1
0 []
1 [1]
2 []
----------------------------------------------------
{1=1, 2=3}
Maximum frequency: 0
0 []
2 []
----------------------------------------------------