Skip to content

Commit 09eed96

Browse files
committed
top-k-frequent-elements solution
1 parent 4bf599c commit 09eed96

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

top-k-frequent-elements/sj.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import java.util.*;
2+
class Solution {
3+
public int[] topKFrequent(int[] nums, int k) {
4+
Map<Integer,Integer> count = new HashMap<>();
5+
for(int i=0;i<nums.length;i++){
6+
count.put(nums[i],count.getOrDefault(nums[i],0)+1);
7+
}
8+
List<Integer> sortedCount = new ArrayList<>(count.keySet());
9+
sortedCount.sort((a,b)->count.get(b)-count.get(a));//value 기준 키 정렬
10+
int[] answer = new int[k];
11+
for(int i=0;i<k;i++){
12+
answer[i] = sortedCount.get(i);
13+
}
14+
15+
return answer;
16+
}
17+
}

0 commit comments

Comments
 (0)