思路
-
一分为二
,递归
求解
- 最后
合并
- 子问题 :
两个升序链表的归并
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if(lists.size() == 0) return nullptr;
if(lists.size() == 1) return lists[0];
// 一分为2
int mid = lists.size() / 2;
vector<ListNode*> left = vector<ListNode*> (lists.begin(), lists.begin() + mid);
vector<ListNode*> right = vector<ListNode*> (lists.begin() + mid, lists.end());
// 递归处理
ListNode *l1 = mergeKLists(left), *l2 = mergeKLists(right);
// 最后归并
return merge2lists(l1, l2);
}
ListNode *merge2lists(ListNode *l1, ListNode* l2)
{
ListNode *dummy = new ListNode(-1);
ListNode *cur = dummy;
while(l1 && l2)
{
if(l1 -> val <= l2 -> val)
{
cur = cur -> next = l1;
l1 = l1 -> next;
}
else
{
cur = cur -> next = l2;
l2 = l2 -> next;
}
}
cur -> next = l1 ? l1 : l2;
return dummy -> next;
}
};