LeetCode--Merge k Sorted Lists

題意:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

題解:建立一個大小爲k的最小堆,即堆頂存放最小元素,因爲k個鏈表已排好序,借鑑歸併排序的技巧,先取出堆頂的元素,再放入堆頂元素所在鏈表的表頭的元素,再維持最小堆循環迭代。
注意直接鏈表存入會導致逆序,可以先存入vector,再逆序存入鏈表。

代碼如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int insertNode(ListNode** head,int val)
    {
        ListNode* newNode = new ListNode(val);
        newNode->next = *head;
        *head = newNode;
        return 0;
    }
    class qNode{
    public:
        int val;
        int index;
        friend bool operator<(qNode a,qNode b){
            return a.val > b.val;
            //val小的優先級高,先從queue pop出來
        }
    };
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        priority_queue<qNode> q;
        vector<int> tmp;
        qNode now,next;
        ListNode* head = NULL;
        for(int i = 0;i < lists.size();i++){
            if(lists[i] != NULL){
                now.val = lists[i]->val;
                lists[i] = lists[i]->next;
                now.index = i;
                q.push(now);
            }
        }
        while(!q.empty()){
            now = q.top();
            q.pop();
            tmp.push_back(now.val);
            if(lists[now.index] != NULL){
                next.val = lists[now.index]->val;
                next.index = now.index;
                q.push(next);
                lists[now.index] = lists[now.index]->next;
            }
        }
        for(int i = tmp.size()-1;i >= 0;i--)
        {
            insertNode(&head,tmp[i]);
        }
        return head;
    }
};
發佈了99 篇原創文章 · 獲贊 6 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章