题解 | 合并k个已排序的链表
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6?tpId=295&tqId=724&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
ListNode dummy(0);
ListNode *cur=&dummy;
while(pHead1!=nullptr&&pHead2!=nullptr){
if(pHead1->val<pHead2->val){
cur->next=pHead1;
pHead1=pHead1->next;
}
else{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;
}
cur->next=pHead1?pHead1:pHead2;
return dummy.next;
}
ListNode* mergeKLists(vector<ListNode*>& lists,int left,int right) {
// write code here
if(left > right)
return NULL;
//中间一个的情况
else if(left == right)
return lists[left];
//从中间分成两段,再将合并好的两段合并
int mid = (left + right) / 2;
return Merge(mergeKLists(lists, left, mid), mergeKLists(lists, mid + 1, right));
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
//k个链表归并排序
return mergeKLists(lists, 0, lists.size() - 1);
}
};
查看9道真题和解析