File tree Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Expand file tree Collapse file tree 1 file changed +29
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .ArrayList ;
2+ import java .util .Collections ;
3+ import java .util .HashMap ;
4+ import java .util .List ;
5+ import java .util .Map ;
6+
7+ class Solution {
8+ public int [] topKFrequent (int [] nums , int k ) {
9+ HashMap <Integer , Integer > hm = new HashMap <>();
10+
11+ for (int num : nums ) {
12+ hm .put (num , hm .getOrDefault (num , 0 )+1 );
13+ }
14+
15+ List <Map .Entry <Integer , Integer >> list = new ArrayList <>(hm .entrySet ());
16+ list .sort (Map .Entry .comparingByValue (Collections .reverseOrder ()));
17+
18+ int index = 1 ;
19+ ArrayList <Integer > answer = new ArrayList <>();
20+ for (Map .Entry <Integer , Integer > entry : list ) {
21+ if (index > k ) break ;
22+ answer .add (entry .getKey ());
23+ index ++;
24+ }
25+
26+ return answer .stream ().mapToInt (Integer ::intValue ).toArray ();
27+ }
28+ }
29+
You can’t perform that action at this time.
0 commit comments