/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} 构造函数 * }; */ #include <queue> #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param lists ListNode类vector * @return ListNode类 */ struct cmp{ bool operator ()(ListNode* a,ListNode* b){ return a->val>b->val; } }; priority_queue<ListNode*,vector<ListNode*>,cmp>pq; ListNode* mergeKLists(vector<ListNode*>& lists) { for(int i=0;i<lists.size();i++){ if(lists[i]!=NULL)pq.push(lists[i]); } ListNode* res=new ListNode(-1); ListNode* head=res; while(!pq.empty()){ ListNode* temp=pq.top(); pq.pop(); head->next=temp; head=head->next; if(temp->next!=NULL)pq.push(temp->next); } return res->next; } };
第1题 【算法讲解027【必备】堆结构常见题】 https://www.bilibili.com/video/BV1Gm4y1p7UE/?share_source=copy_web&vd_source=5065fa61022691e8df35c771a30e6d29