Run Code
|
API
|
Code Wall
|
Users
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
get top k frequent elements ( Priority Queue implementation ) Language: Editor: Layout:
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.*; import java.lang.*; class Rextester { public List<Integer> topKFrequent(int[] nums, int k) { Map<Integer,Integer> mp = new HashMap<>(); for(int i:nums){ mp.put(i,mp.containsKey(i)?mp.get(i)+1:1); } PriorityQueue<Tuple> pq = new PriorityQueue<Tuple>(mp.size()+2,new CustomComparer()); for(int key : mp.keySet()){ pq.add(new Tuple(key,mp.get(key))); } List<Integer> out = new ArrayList<>(); for(int i=0;i<k;i++){ out.add(pq.poll().item); } return out; } } class Tuple{ int item; int count; Tuple(int item,int count){ this.item = item; this.count = count; } } class CustomComparer implements Comparator<Tuple>{ public int compare(Tuple t1, Tuple t2) { if (t1.count < t2.count) return 1; else if (t1.count > t2.count) return -1; return 0; } }
run
|
edit
|
history
|
help
0
Please
log in
to post a comment.
Java Object Graph Dumper (iterative)
Ways to form Max Heap
Abhay
Eckhart generator with real id
Main.java
Integer to English Words
linked lists
練習問題
anonymous abstract class
true false
Please log in to post a comment.