Top K frequent numbers
Java
Medium
5 views
Problem Description
Task: return k numbers with highest frequency. If tie, any order is fine.
Output Format
Return value
Constraints
Use min-heap by frequency.
Official Solution
static int[] topK(int[] a,int k){java.util.HashMap<Integer,Integer> m=new java.util.HashMap<>();for(int x:a) m.put(x,m.getOrDefault(x,0)+1);java.util.PriorityQueue<int[]> pq=new java.util.PriorityQueue<>((u,v)->Integer.compare(u[1],v[1]));for(java.util.Map.Entry<Integer,Integer> e:m.entrySet()){pq.add(new int[]{e.getKey(),e.getValue()});if(pq.size()>k) pq.poll();}int[] res=new int[pq.size()];for(int i=res.length-1;i>=0;i--) res[i]=pq.poll()[0];return res;}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!