Skip to content

Commit 9e567e5

Browse files
committed
add solution: Top K Frequent Elements
1 parent 8f48c5b commit 9e567e5

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// ๊ฐ ์ˆ˜์˜ ๊ฐœ์ˆ˜๋ฅผ ์นด์šดํŠธ ํ•˜๊ณ  ์นด์šดํŠธ ํ•œ ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•˜์—ฌ ์šฐ์„ ์ˆœ์œ„ ํ๋กœ
2+
// k๊ฐœ๋ฅผ ์ถ”์ถœํ•˜์—ฌ result ๋ฆฌ์ŠคํŠธ์— ๋‹ด๋Š”๋‹ค.
3+
4+
// ์‹œ๊ฐ„๋ณต์žก๋„ : O(NlogN)
5+
// ๊ณต๊ฐ„๋ณต์žก๋„ : O(N)
6+
7+
8+
public class SolutionGotprgmer {
9+
10+
public int[] topKFrequent(int[] nums, int k) {
11+
Map<Integer, Integer> map = new HashMap<>();
12+
for(int num:nums){
13+
map.put(num,map.getOrDefault(num,0)+1);
14+
}
15+
PriorityQueue<Map.Entry<Integer, Integer>> pq = new PriorityQueue<>(
16+
(e1, e2) -> e2.getValue().compareTo(e1.getValue())
17+
);
18+
for (Map.Entry<Integer,Integer> entry : map.entrySet()){
19+
pq.offer(entry);
20+
}
21+
22+
int[] result = new int[k];
23+
for(int ansIdx=0;ansIdx < k; ansIdx++){
24+
result[ansIdx] = pq.poll().getKey();
25+
}
26+
return result;
27+
}
28+
}

0 commit comments

Comments
ย (0)