일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 시바견
- attribute
- Convert Sorted List to Binary Search Tree
- data science
- 30. Substring with Concatenation of All Words
- concurrency
- Substring with Concatenation of All Words
- 109. Convert Sorted List to Binary Search Tree
- Regular Expression
- iterator
- Python Implementation
- Python Code
- Decorator
- Class
- LeetCode
- 프로그래머스
- t1
- Python
- shiba
- DWG
- Generator
- 운영체제
- Protocol
- 밴픽
- 컴퓨터의 구조
- 715. Range Module
- 43. Multiply Strings
- kaggle
- 파이썬
- 315. Count of Smaller Numbers After Self
Archives
- Today
- Total
Scribbling
[Java 101] 347. Top K Frequent Elements with HashMap as a counter, PriorityQueue, 본문
Computer Science/Java
[Java 101] 347. Top K Frequent Elements with HashMap as a counter, PriorityQueue,
focalpoint 2023. 2. 14. 04:22class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counter = new HashMap<>();
for (int num: nums) {
counter.put(num, counter.getOrDefault(num, 0) + 1);
}
Comparator<List<Integer>> comparator = (list1, list2) -> {
for (int i = 0; i < list1.size(); i++) {
int value = list1.get(i) - list2.get(i);
if (value != 0)
return value;
}
return 0;
};
Queue<List<Integer>> pq = new PriorityQueue<>(comparator);
for (var key: counter.keySet()) {
pq.add(List.of(counter.get(key), key));
if (pq.size() > k) pq.poll();
}
return pq.stream().map(x -> x.get(1)).mapToInt(i -> i).toArray();
}
}
class Solution {
public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> counter = new HashMap<>();
for (int num: nums) {
counter.put(num, counter.getOrDefault(num, 0) + 1);
}
Queue<Integer> pq = new PriorityQueue<>(
(num1, num2) -> counter.get(num1) - counter.get(num2)
);
for (var key: counter.keySet()) {
pq.add(key);
if (pq.size() > k) pq.poll();
}
return pq.stream().mapToInt(i -> i).toArray();
}
}
'Computer Science > Java' 카테고리의 다른 글
[Java 101] 76. Minimum Window Substring: Set, HashMap (0) | 2023.02.22 |
---|---|
[Java 101] 125. Valid Palindrome with StringBuilder (0) | 2023.02.21 |
[Java 101] 49. Group Anagrams with HashMap, StringBuilder (0) | 2023.02.14 |
[Java 101] 1. Two Sum with HashMap as a counter (0) | 2023.02.14 |
[Java 101] 242. Valid Anagram with HashMap (0) | 2023.02.14 |