1. 程式人生 > >leetcode_效率題解_23. Merge k Sorted Lists(合併k個有序連結串列)

leetcode_效率題解_23. Merge k Sorted Lists(合併k個有序連結串列)

題目連結
【題目】
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;
}
};