您的位置:首页 > 其它

Leetcode 23. Merge k Sorted Lists

2018-01-30 09:59 423 查看
原题:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

解决方法:

采用归并合并的方法,先两两合并,直到最终只剩下一个列表,就是我们所求结果。

代码:
ListNode* mergeTwoList(ListNode* l1, ListNode* l2){
ListNode dummy(INT_MIN);
ListNode* cur = &dummy;
while(l1 && l2){
if (l1->val < l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return dummy.next;
}

ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.empty())
return NULL;

while(lists.size() > 1){ 
   for(int i = lists.size() -1; i > 0; i-=2){
lists.push_back(mergeTwoList(lists[i], lists[i-1]));
lists.erase(lists.begin() + i);
lists.erase(lists.begin() + i - 1);
}
}

return lists.front();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Leetcode