일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Regular Expression
- 운영체제
- Substring with Concatenation of All Words
- 컴퓨터의 구조
- Generator
- DWG
- shiba
- Python Code
- 43. Multiply Strings
- iterator
- 715. Range Module
- concurrency
- Protocol
- 프로그래머스
- t1
- 시바견
- kaggle
- Python
- 밴픽
- 30. Substring with Concatenation of All Words
- data science
- attribute
- Decorator
- Python Implementation
- LeetCode
- 109. Convert Sorted List to Binary Search Tree
- 파이썬
- Convert Sorted List to Binary Search Tree
- Class
- 315. Count of Smaller Numbers After Self
Archives
- Today
- Total
Scribbling
[C++] Priority Queue with custom data type 본문
https://leetcode.com/problems/merge-k-sorted-lists/description/
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
struct ListNodeComparator {
int operator()(ListNode* node1, ListNode* node2) {
return node1->val > node2->val;
// return node2->val - node1->val;
}
};
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* ret = new ListNode();
ListNode* cur = ret;
priority_queue<ListNode*, vector<ListNode*>, ListNodeComparator> pq;
for (ListNode* node : lists) {
if (node != nullptr) pq.push(node);
}
while (not pq.empty()) {
ListNode* node = pq.top();
cur->next = node;
pq.pop();
cur = node;
if (node->next != nullptr) {
pq.push(node->next);
}
}
return ret->next;
}
};
With Lambda: (C++20)
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* ret = new ListNode();
ListNode* cur = ret;
auto comp = [](ListNode* node1, ListNode* node2) {
return node1->val > node2->val;
};
priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> pq;
for (ListNode* node : lists) {
if (node != nullptr) pq.push(node);
}
while (not pq.empty()) {
ListNode* node = pq.top();
cur->next = node;
pq.pop();
cur = node;
if (node->next != nullptr) {
pq.push(node->next);
}
}
return ret->next;
}
};
'Computer Science > C++' 카테고리의 다른 글
[C++] Virtual Functions (0) | 2024.09.28 |
---|---|
[C++] Regular Expression Matching (0) | 2024.09.26 |
[C++] Abstract Class, Interface, Multiple Inheritance (0) | 2024.02.14 |
[C++] lower_bound (0) | 2024.02.06 |
[C++] Deque<int> (0) | 2024.02.06 |