Skip to content

Commit dd0a5aa

Browse files
committed
solve top k frequent elements problem
1 parent fe794af commit dd0a5aa

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

top-k-frequent-elements/sora0319.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,29 @@
11
import java.util.*;
2+
// 다른 방안
3+
class Solution {
4+
public int[] topKFrequent(int[] nums, int k) {
5+
Map <Integer,Integer> counting = new HashMap<>();
6+
7+
for(int n : nums){
8+
if(!counting.containsKey(n)){
9+
counting.put(n,0);
10+
}
11+
counting.put(n, counting.get(n)+1);
12+
}
13+
14+
List<Map.Entry<Integer,Integer>>countList = new LinkedList<>(counting.entrySet());
15+
countList.sort(Map.Entry.comparingByValue(Comparator.reverseOrder()));
16+
17+
int[] answer = countList.stream()
18+
.limit(k)
19+
.mapToInt(Map.Entry::getKey)
20+
.toArray();
21+
return answer;
22+
}
23+
}
24+
225

26+
// 초안
327
class Solution {
428
public int[] topKFrequent(int[] nums, int k) {
529
Map<Integer,Integer> counts = new HashMap<>();

0 commit comments

Comments
 (0)