|
| 1 | +/** |
| 2 | + * Constraints |
| 3 | + * 1 <= nums.length <= 10^5 |
| 4 | + * -10^4 <= nums[i] <= 10^4 |
| 5 | + * k is in the range [1, the number of unique elements in the array]. |
| 6 | + * It is guaranteed that the answer is unique. |
| 7 | + * |
| 8 | + * Output |
| 9 | + * - int 배열 |
| 10 | + */ |
| 11 | + |
| 12 | +class Solution { |
| 13 | + public int[] topKFrequent(int[] nums, int k) { |
| 14 | + // (1) HashMap + PriorityQueue |
| 15 | + // 시간복잡도 : O(N log N) |
| 16 | + // Runtime : 15ms Beats 38.03% |
| 17 | + // Memory : 48.93MB Beats 20.01% |
| 18 | + Map<Integer, Integer> frequencyMap = new HashMap<>(); |
| 19 | + |
| 20 | + for (int num : nums) { |
| 21 | + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); |
| 22 | + } |
| 23 | + |
| 24 | + PriorityQueue<Map.Entry<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Map.Entry::getValue)); |
| 25 | + |
| 26 | + for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { |
| 27 | + minHeap.offer(entry); |
| 28 | + if (minHeap.size() > k) { |
| 29 | + minHeap.poll(); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + int[] result = new int[k]; |
| 34 | + |
| 35 | + for (int i = 0; i < k; i++) { |
| 36 | + result[i] = minHeap.poll().getKey(); |
| 37 | + } |
| 38 | + |
| 39 | + return result; |
| 40 | + |
| 41 | + // (2) Stream |
| 42 | + // 시간복잡도 : O(N log N) |
| 43 | + // Runtime : 19ms Beats 8.16% |
| 44 | + // Memory : 49.00MB Beats 20.01% |
| 45 | + // Stream에 익숙해지기 위해 공부용 |
| 46 | + return Arrays.stream(nums) |
| 47 | + .boxed() |
| 48 | + .collect(Collectors.groupingBy(num -> num, Collectors.summingInt(num -> 1))) |
| 49 | + .entrySet().stream() |
| 50 | + .sorted((a, b) -> b.getValue() - a.getValue()) |
| 51 | + .limit(k) |
| 52 | + .mapToInt(Map.Entry::getKey) |
| 53 | + .toArray(); |
| 54 | + |
| 55 | + // (3) Array List |
| 56 | + // 시간복잡도 : O(N) |
| 57 | + // Runtime : 13ms Beats 75.77% |
| 58 | + // Memory : 48.44MB Beats 61.68% |
| 59 | + Map<Integer, Integer> frequencyMap = new HashMap<>(); |
| 60 | + for (int num : nums) { |
| 61 | + frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); |
| 62 | + } |
| 63 | + |
| 64 | + List<Integer>[] buckets = new List[nums.length + 1]; |
| 65 | + for (int key : frequencyMap.keySet()) { |
| 66 | + int freq = frequencyMap.get(key); |
| 67 | + if (buckets[freq] == null) { |
| 68 | + buckets[freq] = new ArrayList<>(); |
| 69 | + } |
| 70 | + buckets[freq].add(key); |
| 71 | + } |
| 72 | + |
| 73 | + List<Integer> result = new ArrayList<>(); |
| 74 | + for (int i = buckets.length - 1; i >= 0 && result.size() < k; i--) { |
| 75 | + if (buckets[i] != null) { |
| 76 | + result.addAll(buckets[i]); |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return result.stream().mapToInt(Integer::intValue).toArray(); |
| 81 | + } |
| 82 | +} |
0 commit comments