Skip to content

Commit d4ab0dd

Browse files
author
jinvicky
committed
top k frequent elements solution
1 parent 4f3d5a2 commit d4ab0dd

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
import java.util.PriorityQueue;
4+
5+
/**
6+
* [풀이]
7+
* 1. <숫자: λΉˆλ„μˆ˜>λ₯Ό μ €μž₯ν•˜λŠ” HashMapκ³Ό [λΉˆλ„μˆ˜, 숫자]λ₯Ό μ €μž₯ν•˜λŠ” PriorityQueueλ₯Ό μ„ μ–Έν•œλ‹€.
8+
* 2. HashMap에 μˆ«μžλ³„λ‘œ λΉˆλ„μˆ˜λ₯Ό ν•¨κ»˜ μ €μž₯ν•΄μ„œ ν•΄μ‹œν…Œμ΄λΈ”μ„ λ§Œλ“ λ‹€.
9+
* 3.
10+
* <p>
11+
* [μš°μ„ μˆœμœ„ 큐에 μ‚¬μš©λœ 자료ꡬ쑰]
12+
* 1. 별도 클래슀λ₯Ό μ„ μ–Έ
13+
* 2. μš”κ΅¬μ‚¬ν•­ μžλ£Œν˜• 배열을 μ„ μ–Έν•œλ‹€.
14+
* μ²˜μŒμ—λŠ” 별도 클래슀λ₯Ό μ„ μ–Έν–ˆλ‹€κ°€ 값이 2개이며 μ•Œκ³ λ¦¬μ¦˜ 둜직 μžμ²΄κ°€ μ–΄λ €μ›Œμ„œ int[] ꡬ쑰둜 ν’€μ΄ν–ˆλ‹€.
15+
* (주둜 μ•Œκ³ λ¦¬μ¦˜μ΄ μ–΄λ €μš°λ©΄ 가독성이 λ‚˜μ˜λ”λΌλ„ 자료ꡬ쑰λ₯Ό λ‹¨μˆœν™”ν•˜λŠ” μŠ΅κ΄€μ΄ μžˆλ‹€)
16+
* <p>
17+
* <p>
18+
* [μ–΄λ €μ› λ˜ 점]
19+
* 1. μš°μ„ μˆœμœ„ νλŠ” 맀번 μš”μ†Œκ°€ 좔가될 λ•Œλ§ˆλ‹€ λ‚΄λΆ€ 정렬을 μˆ˜ν–‰ν•˜κΈ° λ•Œλ¬Έμ— 연산을 μˆ˜ν–‰ν•˜λ©΄μ„œ k개λ₯Ό μœ μ§€ν•΄μ•Ό ν•œλ‹€.
20+
* λ˜ν•œ κΈ°μ‘΄ [λΉˆλ„μˆ˜, 숫자]λ₯Ό λ²„λ €μ•Όλ§Œ μ˜¬λ°”λ₯Έ 닡을 λ„μΆœν•  수 μžˆμ—ˆλ‹€.
21+
* 2. [숫자, λΉˆλ„μˆ˜]둜 μ €μž₯ν•˜λŠ” κ²ƒλ§Œ μƒκ°ν–ˆλ”λ‹ˆ λ‚΄λΆ€ 정렬을 μ–΄λ–»κ²Œ ν•˜μ§€ λͺ»ν•΄μ„œ ꡉμž₯히 κ³ λ―Όν–ˆλ‹€. 정닡은 λ°˜λŒ€μ˜€λ‹€.
22+
* </p>
23+
*/
24+
class Solution {
25+
public int[] topKFrequent(int[] nums, int k) {
26+
int[] answer = new int[k];
27+
28+
Map<Integer, Integer> map = new HashMap<>();
29+
for (int n : nums) {
30+
map.put(n, map.getOrDefault(n, 0) + 1);
31+
}
32+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
33+
34+
for (int key : map.keySet()) {
35+
pq.add(new int[]{map.get(key), key});
36+
if (pq.size() > k) {
37+
pq.poll();
38+
}
39+
}
40+
41+
for (int i = 0; i < k; i++) {
42+
if (!pq.isEmpty()) {
43+
answer[i] = pq.poll()[1];
44+
}
45+
}
46+
return answer;
47+
}
48+
}

0 commit comments

Comments
Β (0)