相关题解:
leetcode_效率题解_[python/C++]_21. Merge Two Sorted Lists(合并2个有序链表)
题目链接
【题目】
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
【分析】
想到从第一个链表到最后一个链表逐个合并的思路,当然效率是很低的
但是在leetcode上可以AC(198ms)
解法1:
优先队列优化:
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
std::priority_queue<ListNode*, std::vector<ListNode*>, compare > heap;
ListNode head(0);
ListNode *curNode = &head;
int i, k, n = lists.size();
for (i = 0; i < n; i++)
if (lists[i]) heap.push(lists[i]);
while (!heap.empty()){
curNode->next = heap.top();
heap.pop();
curNode = curNode->next;
if (curNode->next) heap.push(curNode->next);
}
return head.next;
}
struct compare {
bool operator()(const ListNode* l, const ListNode* r) {
return l->val > r->val;
}
};
};
python
利用python优先队列模块
from Queue import PriorityQueue
class Solution(object):
def mergeKLists(self, lists):
dummy = ListNode(None)
curr = dummy
q = PriorityQueue()
for node in lists:
if node: q.put((node.val,node))
while q.qsize()>0:
curr.next = q.get()[1]
curr=curr.next
if curr.next: q.put((curr.next.val, curr.next))
return dummy.next
解法2:递归
效率更高
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int n = lists.size();
if(n == 0){return nullptr;}
else if(n == 1){return lists[0];}
else if(n == 2){return merge2Lists(lists[0],lists[1]);}
else{
vector<ListNode*> part1(lists.begin(), lists.begin() + (n)/2);
vector<ListNode*> part2(lists.begin() + (n)/2 ,lists.end());
return merge2Lists(mergeKLists(part1),mergeKLists(part2));
}
}
ListNode* merge2Lists(ListNode* root1, ListNode* root2){
if(root1 == NULL) return root2;
if(root2 == NULL) return root1;
ListNode dummy(0);
ListNode* p = &dummy;
while(root1 != NULL && root2 != NULL){
if(root1->val >= root2->val){
p->next = root2;
p = p->next;
root2 = root2->next;
}else{
p->next = root1;
p = p->next;
root1 = root1->next;
}
}
if(root1 != NULL){p->next = root1;}
else if (root2 != NULL){p->next = root2;}
return dummy.next;
}
};