일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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
- Generator
- Python
- data science
- Python Implementation
- t1
- Protocol
- 109. Convert Sorted List to Binary Search Tree
- Python Code
- shiba
- 운영체제
- 715. Range Module
- 30. Substring with Concatenation of All Words
- concurrency
- 315. Count of Smaller Numbers After Self
- Class
- 컴퓨터의 구조
- Regular Expression
- Convert Sorted List to Binary Search Tree
- Substring with Concatenation of All Words
- 시바견
- 프로그래머스
- iterator
- kaggle
- 밴픽
- 43. Multiply Strings
- Decorator
- DWG
- 파이썬
- LeetCode
- attribute
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++] Abstract Class, Interface, Multiple Inheritance (0) | 2024.02.14 |
---|---|
[C++] lower_bound (0) | 2024.02.06 |
[C++] Deque<int> (0) | 2024.02.06 |
[C++] 전문가를 위한 C++ - Chapter 8 (0) | 2023.10.07 |
[C++] find, deque, bfs, structured binding (0) | 2023.09.30 |