合成K个以排序的链表

80 阅读1分钟

这里发现一个很有用的技巧,使用优先队列很方便

struct compare {
    bool operator() (ListNode *a, ListNode *b) {
        return a->val > b->val;
    }
};

//这样我们使用优先队列就贼简单,这里只需要用compare就可以了
priority_queue<ListNode*, vector<ListNode*>, compare > listGreatHeap;

链接: www.nowcoder.com/practice/65…

优先队列方法

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if(lists.empty()) return nullptr;

        priority_queue<ListNode*,vector<ListNode*>, compare > listGreaterHeap;
        for (int i=0;i<lists.size();i++) {
            if(lists[i] != nullptr) listGreaterHeap.push(lists[i]);
        }
        ListNode *pHead = new ListNode(0);
        ListNode *now = pHead;
        while(!listGreaterHeap.empty()) {
            ListNode *nex = listGreaterHeap.top();
            listGreaterHeap.pop();

            now->next = nex;
            if(nex->next != nullptr) {
                listGreaterHeap.push(nex->next);
            }
            now = nex;
        }
        return pHead->next;

    }
    struct compare {
        bool operator() (ListNode *a, ListNode *b) {
            return a->val > b->val;
        }
    };


};

归并排序方法:

这里我错了2次,一个是merge函数中,开头没判断2个链表是否为空,另外一个是mergeKthLists开头也没有判断vector中lists中是否为空,还是要多加注意

class Solution {
public:
    ListNode *merge(ListNode *pHead1, ListNode *pHead2) {
        if(pHead1 == nullptr) return pHead2;
        if(pHead2 == nullptr) return pHead1;
        ListNode *pHead = new ListNode(0);
        ListNode *now = pHead;
        while(pHead1 != nullptr && pHead2 != nullptr) {
            if (pHead1->val < pHead2->val ) {
                now->next = pHead1;
                now = pHead1;
                pHead1 = pHead1->next;
            } else {
                now->next = pHead2;
                now = pHead2;
                pHead2 = pHead2->next;
            }
        }
        if(pHead1 != nullptr) {
            now->next = pHead1;
        } else {
            now->next = pHead2;
        }

        return pHead->next;
    }
    ListNode *recursionMerge(vector<ListNode*> &lists,int l,int r) {
        if(l>=r) return lists[l];

        int mid = (l+r)>>1;
        return merge(recursionMerge(lists, l, mid), recursionMerge(lists, mid+1, r));

    }
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if(lists.empty()) return nullptr;
        return recursionMerge(lists, 0, lists.size()-1);
    }
};