|
1 | 1 | import java.util.HashMap;
|
2 | 2 | import java.util.Map;
|
| 3 | +import java.util.PriorityQueue; |
| 4 | + |
| 5 | +// 시간 복잡도: O(nlogk) - 최대 힙에 k개의 요소를 넣는데 O(logk)가 걸리고, 이를 n번 반복 |
| 6 | +// 공간 복잡도: O(n) - 빈도수를 저장하는 freqMap |
3 | 7 | class Solution {
|
4 |
| - public static int[] topKFrequent(int[] nums, int k) { |
5 |
| - Map<Integer, Integer> myMap = new HashMap<>(); |
6 |
| - for (int num : nums) { |
7 |
| - myMap.put(num, myMap.getOrDefault(num, 0) + 1); |
8 |
| - } |
9 |
| - return myMap.entrySet() |
10 |
| - .stream() |
11 |
| - .sorted((v1, v2) -> Integer.compare(v2.getValue(),v1.getValue())) |
12 |
| - .map(Map.Entry::getKey) |
13 |
| - .mapToInt(Integer::intValue) |
14 |
| - .toArray(); |
| 8 | + |
| 9 | + public int[] topKFrequent(int[] nums, int k) { |
| 10 | + Map<Integer, Integer> freqMap = new HashMap<>(); |
| 11 | + for (int num : nums) { |
| 12 | + freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); |
15 | 13 | }
|
| 14 | + |
| 15 | + PriorityQueue<Map.Entry<Integer, Integer>> maxHeap = |
| 16 | + new PriorityQueue<>((a, b) -> b.getValue() - a.getValue()); |
| 17 | + |
| 18 | + // 빈도수를 기준으로 최소 힙에 k개의 요소를 넣기 |
| 19 | + for (Map.Entry<Integer, Integer> entry : freqMap.entrySet()) { |
| 20 | + maxHeap.offer(entry); |
| 21 | + } |
| 22 | + |
| 23 | + int[] result = new int[k]; |
| 24 | + int index = 0; |
| 25 | + while (k > 0) { |
| 26 | + k--; |
| 27 | + result[index++] = maxHeap.poll().getKey(); |
| 28 | + } |
| 29 | + |
| 30 | + return result; |
| 31 | + } |
16 | 32 | }
|
0 commit comments