合并N个有序列表 用优先级队列, 时间O(nlogn), 空间O(n)

合并k个已排序的链表

http://www.nowcoder.com/questionTerminal/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include<queue>
using namespace std;
//给优先级队列定义比较函数。让其从小到大
struct cmp {
    bool operator()(const ListNode *a, const ListNode *b){
        return a->val > b->val; 
    }
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        ListNode L(0);
        ListNode *tail = &L;
        priority_queue<ListNode *, vector<ListNode*>,cmp> Q;
        //队列首部放入堆
        for(auto &nd : lists){
            if(nd == nullptr){
                continue;
            }
            Q.push(nd);
        }
        while(!Q.empty()){
            //堆顶弹出的是最小的
            auto top = Q.top();
            Q.pop();
            if(top->next != nullptr){
                //当前链表的下一个元素插入堆
                Q.push(top->next);
            }
            //构造结果队列
            tail->next = top;
            top->next = nullptr;
            tail = top;
        }
        return L.next;
    }
};
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务