LeetCode之Merge k Sorted Lists

来源:互联网 发布:淘宝 苹果证书 编辑:程序博客网 时间:2024/06/05 03:35
/* 采用最小堆不断将最小的节点加入到结果链表中。 参考自:http://www.cnblogs.com/TenosDoIt/p/3673188.html*/class Solution {public:    ListNode* mergeKLists(vector<ListNode*>& lists) {        if(lists.empty()) return nullptr;ListNode head(-1), *p(&head);        priority_queue<ListNode*, vector<ListNode*>, cmp> q;for(int i = 0; i < lists.size(); ++i){if(lists[i]) q.push(lists[i]);}while(!q.empty()){p->next = q.top();q.pop();if(p->next->next) q.push(p->next->next);p = p->next;}return head.next;    }private:struct cmp{bool operator()(ListNode* a, ListNode* b){return a->val > b->val;}};};/* 采用分治算法进行求解。 参考自:http://www.cnblogs.com/TenosDoIt/p/3673188.html*/class Solution {public:    ListNode* mergeKLists(vector<ListNode*>& lists) {        int n(lists.size());        if(n == 0) return nullptr;        while(n > 1){            int k = (n+1)/2;            for(int i = 0; i < n/2; ++i){                lists[i] = merge2Lists(lists[i], lists[i+k]);            }            n = k;        }        return lists[0];    }        ListNode* merge2Lists(ListNode* l1, ListNode* l2){        ListNode head(-1);        ListNode *p(&head);        while(l1 && l2){            if(l1->val < l2->val){                p->next = l1;                l1 = l1->next;            }            else{                p->next = l2;                l2 = l2->next;            }            p = p->next;        }        if(l1) p->next = l1;        else if(l2) p->next = l2;        return head.next;    }};


                                             
0 0