Merge k Sorted ListsTotal accepted:61378 Total submissions:285515 difficulty:hard
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
The idea is to attach a few orderly lists to the smallest heap in the head of each linked list.
1#include <iostream>2#include <algorithm>//std::make_heap (), std::p op_heap (), std::p ush_heap,std::sort_heap ( )3#include <vector>4 5 usingstd::vector;6 7 structListNode {8 intVal;9ListNode *Next;TenListNode (intx): Val (x), Next (NULL) {} One }; A - classSolution { - Public: thelistnode* mergeklists (vector<listnode*>&lists) { - if(Lists.empty ())returnnullptr; - intn =lists.size (); -Vector<listnode*>minheap; + Minheap.reserve (n); - for(intI=0; i<n;i++) + Minheap.push_back (Lists[i]); AMake_heap (Minheap.begin (), minheap.end (), greater);//construct the first min heap at -ListNode head = ListNode (-1); -ListNode *p= &head; - while(Minheap.front ()! =nullptr) - { -P->next =Minheap.front (); in pop_heap (Minheap.begin (), minheap.end (), greater); - Minheap.pop_back (); toMinheap.push_back (p->next->next); + push_heap (Minheap.begin (), minheap.end (), greater); -P=p->Next; the } * returnHead.next; $ }Panax Notoginseng Private: - Static BOOLGreater (listnode* l1,listnode*L2) { the if(L1 = = nullptr)return true; + Else if(L2 = = nullptr)return false; A Else returnL1->val >= l2->Val; the } + }; - $ intMain () $ { -Vector<listnode*>lists; -listnode* List1 =NewListNode (1); theList1->next =NewListNode (3); -List1->next->next =NewListNode (6);Wuyi thelistnode* List2 =NewListNode (2); -List2->next =NewListNode (4); WuList2->next->next =NewListNode (5); - Aboutlistnode* List3 =NewListNode ( -); $ - Lists.push_back (list1); - Lists.push_back (list2); - Lists.push_back (LIST3); A + solution S; theListNode *head; -Head =s.mergeklists (lists); $ while(head!=nullptr) the { theStd::cout << Head->val <<" -"; theHead = head->Next; the } - return 0; in}
Merge k Sorted Lists