0023. 合并 K 个升序链表 #47
utterances-bot
started this conversation in
Comments
Replies: 0 comments 1 reply
-
附上C++代码
class Solution {
public:
ListNode *mergeSort(vector<ListNode *> &lists, int l, int r) {
if(l == r) return lists[l];
int mid = l+((r-l)>>1);
ListNode *left = mergeSort(lists, l, mid);
ListNode *right = mergeSort(lists, mid+1, r);
return merge(left, right);
}
ListNode *merge(ListNode *lists1, ListNode *lists2) {
ListNode *node = new ListNode(0);
ListNode *tmp = node;
while(lists1 && lists2) {
if(lists1->val <= lists2->val) {
tmp->next = lists1;
lists1 = lists1->next;
} else {
tmp->next = lists2;
lists2 = lists2->next;
}
tmp = tmp->next;
}
if(lists1) tmp->next = lists1;
if(lists2) tmp->next = lists2;
return node->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if(n == 0) return nullptr;
if(n == 1) return lists[0];
return mergeSort(lists, 0, n-1);
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
0023. 合并K个升序链表 | 算法通关手册
https://algo.itcharge.cn/Solutions/0001-0099/merge-k-sorted-lists/
Beta Was this translation helpful? Give feedback.
All reactions