| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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
- concurrency
- kaggle
- 715. Range Module
- Python Code
- 파이썬
- 밴픽
- Class
- Convert Sorted List to Binary Search Tree
- 컴퓨터의 구조
- DWG
- 프로그래머스
- 30. Substring with Concatenation of All Words
- data science
- Regular Expression
- iterator
- t1
- Generator
- attribute
- shiba
- 시바견
- LeetCode
- 43. Multiply Strings
- 315. Count of Smaller Numbers After Self
- Decorator
- 운영체제
- Python Implementation
- Python
- Substring with Concatenation of All Words
- Protocol
- 109. Convert Sorted List to Binary Search Tree
Archives
- Today
- Total
Scribbling
[C++] Priority Queue with custom data type 본문
https://leetcode.com/problems/merge-k-sorted-lists/description/
LeetCode - The World's Leading Online Programming Learning Platform
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
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 |