Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
get top k frequent elements ( Priority Queue implementation )
//'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
클래스의 정의와 인스턴스 생성
4.A
jkbvlghckgh
Write a program to sort the odd elements descending order and even elements in ascending order
JAVA # DİZİ İLE EN BÜYÜK BULMA
victory1
2.C
1d
LCM using recursion
classwork