题目
代码(首刷看解析,lambda优先队列)
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> q(cmp);
for(auto& node : lists) {
if(node) // 防止插入空指针
q.push(node);
}
auto head = new ListNode(0);
auto p = head;
while(!q.empty()) {
p->next = q.top();
p = p->next;
q.pop();
if(p->next)
q.push(p->next);
}
return head->next;
}
};
代码(8.7 二刷自解)
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](ListNode* a, ListNode* b) { return a->val > b->val;};
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> q(cmp);
for(auto node : lists) {
if(node) q.push(node);
}
auto dummy = new ListNode(0);
auto p = dummy;
while(!q.empty()) {
auto top = q.top();
p->next = top;
q.pop();
if(top->next)
q.push(top->next);
p = p->next;
}
return dummy->next;
}
};
学习GO的小根堆
func mergeKLists(lists []*ListNode) *ListNode {
if len(lists) == 0 {return nil}
h := IntHeap{}
heap.Init(&h)
for _, list := range lists {
if list != nil {
heap.Push(&h, list)
}
}
dummy := &ListNode{}
p := dummy
for h.Len() > 0 {
top := heap.Pop(&h).(*ListNode)
p.Next = top
p = p.Next
if top.Next != nil {
heap.Push(&h, top.Next)
}
}
return dummy.Next
}
type IntHeap []*ListNode
func (h IntHeap) Less(i, j int) bool { return h[i].Val < h[j].Val}
func (h IntHeap) Swap(i, j int) {h[i], h[j] = h[j], h[i]}
func (h IntHeap) Len() int { return len(h) }
func (h *IntHeap) Push(x interface{}) {*h = append(*h, x.(*ListNode))} // 这两个函数顶层是interface{}
func (h *IntHeap) Pop() interface{} {
n := len(*h)
ans := (*h)[n-1]
*h = (*h)[:n-1]
return ans
}
代码(9.8 三刷看解析 归并)
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
return merge(lists, 0, lists.size()-1);
}
ListNode* merge(vector<ListNode*>& lists, int l, int r) {
if(l == r)
return lists[l];
if(l > r)
return nullptr;
int mid = (l+r)/2;
return merge2Lists(merge(lists, l, mid), merge(lists, mid+1, r));
}
ListNode* merge2Lists(ListNode* a, ListNode* b) {
if(!a || !b)
return a ? a : b;
ListNode head, *tail = &head;
auto aptr = a, bptr = b;
while(aptr && bptr) {
if(aptr->val < bptr->val) {
tail->next = aptr;
aptr = aptr->next;
} else {
tail->next = bptr;
bptr = bptr->next;
}
tail = tail->next;
}
if(aptr) tail->next = aptr;
else tail->next = bptr;
return head.next;
}
};
自解
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
auto cmp = [](auto& a, auto& b) { return a->val > b->val; };
priority_queue<ListNode*, vector<ListNode*>, decltype(cmp)> q(cmp);
for(auto& l : lists) {
if(l)
q.push(l);
}
ListNode ans, *tail = &ans;
while(!q.empty()) {
auto top = q.top();
q.pop();
tail->next = top;
tail = tail->next;
if(top->next)
q.push(top->next);
}
return ans.next;
}
};