Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
get top k frequent elements ( Priority Queue implementation )
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
//'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; } }
[
+
]
Show input
edit mode
|
history
|
discussion