每次从K个值中用最小堆来获取到K个值中的最小值
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 struct Status { 14 int val; 15 ListNode *ptr; 16 bool operator < (const Status &rhs) const { 17 return val > rhs.val; 18 } 19 }; 20 21 priority_queue <Status> q; 22 23 ListNode* mergeKLists(vector<ListNode*>& lists) { 24 for (auto node: lists) { 25 if (node) q.push({node->val, node}); 26 } 27 ListNode head, *tail = &head; 28 while (!q.empty()) { 29 auto f = q.top(); q.pop();//堆中最小 30 tail->next = f.ptr; 31 tail = tail->next; 32 if (f.ptr->next) q.push({f.ptr->next->val, f.ptr->next});//堆重新调整 33 } 34 return head.next; 35 } 36 };
每天进步一点点~