Run Code
|
API
|
Code Wall
|
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
codesingnal Code
OBF-7
binary search
reservation vehicules
evenloop
Iterative Merge sort
LeetCode 121 - Best time to buy and sell stock - O(n) solution
mostrar pam
DFS in Graph
Star