Skip to content

Commit 325d1b2

Browse files
committed
top K Frequent
1 parent 53ce7c7 commit 325d1b2

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

contains-duplicate/Geegong.java

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import java.util.HashMap;
2+
import java.util.HashSet;
3+
import java.util.Iterator;
4+
import java.util.Map;
5+
6+
public class Geegong {
7+
8+
public int[] topKFrequent(int[] nums, int k) {
9+
int[] result = new int[k];
10+
11+
// key : key / value : count
12+
Map<Integer, Integer> keyMap = new HashMap<>();
13+
14+
// key : count / value : HashSet<Integer> keys
15+
Map<Integer, HashSet<Integer>> countMap = new HashMap<>();
16+
17+
// 가장 많이 출연한 친구
18+
int maxCount = 0;
19+
20+
for (int num : nums) {
21+
int countToBePut = 0;
22+
23+
if (keyMap.containsKey(num)) {
24+
Integer alreadyCounted = keyMap.get(num);
25+
countToBePut = alreadyCounted + 1;
26+
keyMap.put(num, countToBePut);
27+
28+
checkCountMapAndPutCount(countMap, num, countToBePut);
29+
} else {
30+
countToBePut = 1;
31+
keyMap.put(num, countToBePut);
32+
checkCountMapAndPutCount(countMap, num, countToBePut);
33+
}
34+
35+
maxCount = Math.max(maxCount, countToBePut);
36+
}
37+
38+
39+
// 가장 큰 숫자부터 꺼내볼까요오오오 우후
40+
int kIndex=0;
41+
for (int index=maxCount; index >= 0; index--) {
42+
if (kIndex >= k) {
43+
return result;
44+
}
45+
46+
if (countMap.containsKey(index)) {
47+
HashSet<Integer> hashNums = countMap.get(index);
48+
Iterator<Integer> iterator = hashNums.iterator();
49+
while(iterator.hasNext()) {
50+
51+
if (kIndex >= k) {
52+
return result;
53+
}
54+
55+
result[kIndex] = iterator.next();
56+
kIndex++;
57+
}
58+
59+
}
60+
61+
}
62+
63+
return result;
64+
65+
66+
}
67+
68+
public void checkCountMapAndPutCount(Map<Integer, HashSet<Integer>> countMap, int key, int count) {
69+
if (countMap.containsKey(count)) {
70+
HashSet<Integer> already = countMap.get(count);
71+
already.add(key);
72+
} else {
73+
HashSet<Integer> newSet = new HashSet<>();
74+
newSet.add(key);
75+
countMap.put(count, newSet);
76+
}
77+
78+
}
79+
80+
}

0 commit comments

Comments
 (0)