Leetcode -- Merge k Sorted Lists

来源:互联网 发布:c语言经典编程282例txt 编辑:程序博客网 时间:2024/05/22 10:52

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


本题使用优先队列,自定义优先级。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    struct cmp    {        bool operator ()(pair<int,int> &a,pair<int,int> &b)        {            return a.first>b.first;        }    };    ListNode* mergeKLists(vector<ListNode*>& lists) {        ListNode *h = new ListNode(-1),*p = h;        priority_queue<pair<int,int>,vector<pair<int,int> >,cmp> que;        int n = lists.size();        for(int i=0;i<n;++i)            if(lists[i])            {                que.push(make_pair(lists[i]->val,i));            }                while(!que.empty())        {            auto tmp = que.top();            que.pop();            int val = tmp.first,idx = tmp.second;            p->next = lists[idx];            lists[idx] = lists[idx]->next;            if(lists[idx])            {                que.push(make_pair(lists[idx]->val,idx));            }            p = p->next;        }        p = h->next;        delete h;        return p;    }};


0 0