Merge k Sorted Lists

来源:互联网 发布:淘宝产品打折功能收费 编辑:程序博客网 时间:2024/06/05 10:00

Merge k Sorted Lists

原题链接:https://leetcode.com/problems/merge-k-sorted-lists/description/

题目要求将k个已排好序(升序)的链表,合并成一个有序的链表。

Solution1: 第一种方法就是,用分治法,先将这k个list两两合并,得到k/2个长度为2n的新链表;然后继续将这k/2个链表两两合并,直到最后合并成一个链表。

ListNode* mergeKLists(vector<ListNode*>& lists) {        int k = lists.size();        if (k == 0) return NULL;        if (k == 1) return lists[0];        vector<ListNode*> A(lists.begin(), lists.begin() + k/2);        vector<ListNode*> B(lists.begin() + k/2, lists.end());        ListNode* list_A = mergeKLists(A);        ListNode* list_B = mergeKLists(B);        ListNode *result = NULL, *tempNode;        while(list_A || list_B) {  // list 都是升序            if (!list_A) {                                if (!result) {                    result = new ListNode(list_B->val);                    result -> next  = list_B -> next;                } else {                    tempNode->next = list_B;                }                break;            }            if (!list_B) {                while (list_A) {                    if (!result) {                        result = new ListNode(list_A->val);                        tempNode = result;                    } else {                        tempNode->next = new ListNode(list_A->val);                        tempNode = tempNode -> next;                    }                    list_A = list_A -> next;                }                break;            }            int value_A = list_A->val;            int value_B = list_B->val;            if (!result) {                result = new ListNode(min(value_A, value_B));                tempNode = result;            } else {                tempNode->next = new ListNode(min(value_A, value_B));                tempNode = tempNode -> next;            }            if (value_A < value_B) list_A = list_A -> next;             else list_B = list_B -> next;        }        return result;    }

算法复杂度: 假设k个list共有N个节点,则复杂度为O(Nlogk)。

Solution2: 可以使用priority_queue这种数据结构,因为priority_queue的第一个元素是它所包含的元素中最大或最小的。将k个list中所有节点的数据都存入priority_queue中,并根据这个priority_queue重新生成一个链表。

struct compareNodes {    bool operator()(const int a, const int b) {        return a > b;    }};class Solution {public:    ListNode* mergeKLists(vector<ListNode*>& lists) {        priority_queue<int, vector<int>, compareNodes> p;        for (auto l : lists) {            while (l) {                p.push(l -> val);                l = l->next;            }        }        ListNode* result = NULL, *tail;        if (!p.empty()) {            result = new ListNode(p.top());            tail = result;            p.pop();        }        while (!p.empty()) {            tail -> next = new ListNode(p.top());            tail = tail -> next;            p.pop();        }        return result;    }};

算法复杂度: 查找优先队列中的最小值,需要O(1),插入和删除需要O(logN),其中N为优先队列中元素个数。所以,假设k个list共有N个节点,这种方法的复杂度为O(NlogN)。
改进:若在k路归并中使用优先队列来选择最小值,则只需要构建一个长度为k的优先队列,因此时间复杂度可以达到O(Nlogk)。