Leetcode刷题 - 多路归并类(K-way merge)

21. 合并两个有序链表 - Merge Two Sorted Lists

题目:https://leetcode.com/problems/merge-two-sorted-lists/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        //利用递归
        //哪个list为null,则说明另一个list存了所有的结果
        if (l1 == NULL) return l2;
        if (l2 == NULL) return l1;
        //小的数放在最前面
        if (l1->val >= l2 -> val) l2->next = mergeTwoLists(l1, l2->next);
        else {
            l1->next = mergeTwoLists(l1->next, l2);
            //确保最终结果在l2上
            l2 = l1;
        }
        
        return l2;
        
    }
};

23. 合并k个有序链表 - Merge k Sorted Lists

题目:https://leetcode.com/problems/merge-k-sorted-lists/

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
             // heap
        auto comp = [](ListNode* a, ListNode* b){return a->val > b->val;};
        priority_queue<ListNode *, vector<ListNode *>, decltype(comp)> pq(comp); 
        
        for (auto list : lists){
            if (list) pq.push(list);
        }
        if (pq.empty()) return NULL;
        ListNode * result = pq.top();
        pq.pop();
        // 判断NULL情况
        if (result->next) pq.push(result->next);
        ListNode*newList = result;
        while (!pq.empty()){
            newList->next = pq.top();
            pq.pop();
            newList = newList -> next;
            // 判断NULL情况
            if (newList->next) pq.push(newList->next);
        }
        
        return result;
    }
};

  

 

posted @ 2020-09-13 11:46  cancantrbl  阅读(401)  评论(0编辑  收藏  举报