일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- t1
- Python Code
- 컴퓨터의 구조
- concurrency
- DWG
- 30. Substring with Concatenation of All Words
- iterator
- 315. Count of Smaller Numbers After Self
- 파이썬
- 운영체제
- kaggle
- Regular Expression
- Generator
- 109. Convert Sorted List to Binary Search Tree
- 시바견
- Class
- 715. Range Module
- Convert Sorted List to Binary Search Tree
- Python Implementation
- Decorator
- data science
- LeetCode
- shiba
- 프로그래머스
- Protocol
- 밴픽
- attribute
- Substring with Concatenation of All Words
- 43. Multiply Strings
- Python
Archives
- Today
- Total
Scribbling
[C++] priority queue (vector<int>) with comparator 본문
Computer Science/C++
[C++] priority queue (vector<int>) with comparator
focalpoint 2023. 8. 18. 05:52
LeetCode 347. Top K Frequent Elements
https://leetcode.com/problems/top-k-frequent-elements/
Top K Frequent Elements - LeetCode
Can you solve this real interview question? Top K Frequent Elements - Given an integer array nums and an integer k, return the k most frequent elements. You may return the answer in any order. Example 1: Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
leetcode.com
struct my_comparator
{
bool operator()(std::vector<int> const& a, std::vector<int> const& b) const
{
// smallest to top (min heap)
return a[0] > b[0];
}
};
using custom_priority_queue = std::priority_queue<std::vector<int>, std::vector<std::vector<int>>, my_comparator>;
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> counter;
for (auto num : nums) {
counter[num]++;
}
custom_priority_queue pq;
for (auto e : counter) {
vector<int> tmp;
tmp.push_back(e.second);
tmp.push_back(e.first);
pq.push(tmp);
if (pq.size() > k) {
pq.pop();
}
}
vector<int> ret;
while (!pq.empty()) {
vector<int> tmp = pq.top();
pq.pop();
ret.push_back(tmp[1]);
}
return ret;
}
};
'Computer Science > C++' 카테고리의 다른 글
[C++] LeetCode 128. Longest Consecutive Sequence (0) | 2023.08.18 |
---|---|
[C++] LeetCode 238. Product of Array Except Self (0) | 2023.08.18 |
[C++] 49. Group Anagrams (0) | 2023.08.18 |
[C++] LeetCode 242. Valid Anagram (0) | 2023.08.18 |
[C++] LeetCode 217. Contains Duplicate (0) | 2023.08.18 |