I am facing problems while coding in java
Top k most frequent
Here is My code: import java.util.*; class Main{ static class Pair{ int data; int freq; Pair(int data, int freq){ this.data = data; this.freq = freq; } public int compareTo(Pair o){ if(this.freq == o.freq) return this.data - o.data; return o.freq-this.freq; } } public static void solve(){ PriorityQueue pq = new PriorityQueue<>(); HashMap<Integer, Integer> map = new LinkedHashMap<>(); int n = scn.nextInt(); int k = scn.nextInt(); while(n–>0){ int val = scn.nextInt(); if(map.containsKey(val)){ map.put(val,map.get(val)+1); }else{ map.put(val,1); } } for(Map.Entry<Integer, Integer> entry : map.entrySet()){ pq.add(new Pair(entry.getKey(),entry.getValue())); int count = 0; Iterator it = pq.iterator(); while(count<k && it.hasNext()){ System.out.print(it.next().data+" "); count++; } } } public static Scanner scn = new Scanner(System.in); public static void main(String[] args){ int t = scn.nextInt(); while(t–>0){ solve(); } } }
Code is not working ? Please help:\
Anybody? TAsss? I had posted this doubt yesterday. No-one is replying
@ap8730390
you don’t have to fill the HashMap completely you have to process as the new number is read. then you have to print the top k numbers.
for this sample input:
1
5 2
5 1 3 5 2
first input 5:
freq 5->1
output: 5
second input 1:
freq 5->1
1->1
now both have the same you freq you have to print in inc order of their value.
output: 5 1 5
third input 3
freq 5->1
1->1
3->1
all have the same freq you have to print in inc order of their value.
output: 5 1 5 1 3
fourth input 5:
freq 5->2
1->1
3->1
top k element are 5 and 1
output: 5 1 5 1 3 5 1
fifth input 2:
freq 5->2
1->1
3->1
2->1
top k elements are 5 and 1
final output:5 1 5 1 3 5 1 5 1
I hope you understand it. if you have any doubt feel free to ask: 
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.