File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change 1+ import java .util .Arrays ;
2+ import java .util .HashMap ;
3+ import java .util .Map ;
4+
5+ class SolutionTopKFrequentElements {
6+ public int [] topKFrequent (int [] nums , int k ) {
7+ // ๋น๋์์ผ๋ก k๊ฐ ๋ฐํ
8+ // ๋น๋ ์ฒดํฌ: ํด์๋งต์ผ๋ก ์นด์ดํธ. ์๊ฐ๋ณต์ก๋ O(N), ๊ณต๊ฐ๋ณต์ก๋ O(N)
9+ // ๋น๋์ ์ ๋ ฌ: sorting, ์๊ฐ๋ณต์ก๋ O(N log N), ๊ณต๊ฐ๋ณต์ก๋ O(N)
10+ // ํฉ์ฐ: ์๊ฐ๋ณต์ก๋ O(N log N), ๊ณต๊ฐ๋ณต์ก๋ O(N)
11+
12+ // ๋น๋ ์ฒดํฌ
13+ Map <Integer , Integer > freq = new HashMap <>();
14+ for (int num : nums ) {
15+ freq .put (num , freq .getOrDefault (num , 0 ) + 1 );
16+ }
17+
18+ // ๋น๋์ ์ ๋ ฌ
19+ int [] sortedNums = freq .keySet ().stream ()
20+ .sorted ((a , b ) -> freq .get (b ) - freq .get (a ))
21+ .mapToInt (i -> i )
22+ .toArray ();
23+
24+ // ๋ฐฐ์ด์์ ์์ k๊ฐ๋ง ๋ฐํ
25+ return Arrays .copyOf (sortedNums , k );
26+ }
27+ }
You canโt perform that action at this time.
0 commit comments