LeetCode 22. Merge k Sorted Lists

来源:互联网 发布:视觉检测软件 编辑:程序博客网 时间:2024/05/29 16:19

用一个最小堆盛放所有有序链表的头结点即可。

复杂度O(nlogm) -- n为结点总数,m为vector.size()


代码:

class Solution {public:struct cmp{bool operator () (const ListNode* a, const ListNode* b){return a->val > b->val;}};ListNode *mergeKLists(vector<ListNode *> &lists) {ListNode *head=NULL, *cur=NULL;priority_queue<ListNode*, vector<ListNode*>, cmp> ss;for (auto it = lists.begin(); it != lists.end(); ++ it){if (*it != NULL){ss.push(*it);}}while(ss.empty() == false){auto top = ss.top();if (head == NULL){head = cur = top;} else{cur->next = top;cur = cur->next;}ss.pop();if (top->next != NULL){ss.push(top->next);}}return head;}};


0 0
原创粉丝点击