合并k个已排序的链表_牛客题霸_牛客网 (nowcoder.com)
class Solution {
public:
//两个有序链表合并函数
ListNode* Merge2(ListNode* pHead1, ListNode* pHead2) {
if(!pHead1) return pHead2;
if(!pHead2) return pHead1;
if(pHead1->val < pHead2->val){
pHead1->next = Merge2(pHead1->next,pHead2);
return pHead1;
}else{
pHead2->next = Merge2(pHead2->next,pHead1);
return pHead2;
}
}
//划分合并区间函数
/*
step 1:从链表数组的首和尾开始,每次划分从中间开始划分,划分成两半,得到左边
n/2个链表和右边 n/2个链表。
step 2:继续不断递归划分,直到每部分链表数为1.
*/
ListNode* divideMerge(vector<ListNode*>& lists, int left, int right) {
if(left > right) return nullptr;
if(left == right) return lists[left];
int mid = left + (right - left)/2;
return Merge2(divideMerge(lists,left,mid),divideMerge(lists,mid+1,right));
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
//k个链表归并排序
return divideMerge(lists, 0, lists.size() - 1);
}
};