标签:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
将几个有序的链表连接起来,思路是把每个链表的头部放在一个最小堆中。
1 #include <iostream> 2 #include <algorithm> //std::make_heap(),std::pop_heap(),std::push_heap,std::sort_heap() 3 #include <vector> 4 5 using std::vector; 6 7 struct ListNode { 8 int val; 9 ListNode *next; 10 ListNode(int x) : val(x), next(NULL) {} 11 }; 12 13 class Solution { 14 public: 15 ListNode* mergeKLists(vector<ListNode*>& lists) { 16 if(lists.empty()) return nullptr; 17 int n = lists.size(); 18 vector<ListNode*> minHeap; 19 minHeap.reserve(n); 20 for(int i=0;i<n;i++) 21 minHeap.push_back(lists[i]); 22 make_heap(minHeap.begin(),minHeap.end(),greater); //construct the first min heap 23 24 ListNode head = ListNode(-1); 25 ListNode *p= &head; 26 while(minHeap.front() != nullptr) 27 { 28 p->next = minHeap.front(); 29 pop_heap(minHeap.begin(), minHeap.end(),greater); 30 minHeap.pop_back(); 31 minHeap.push_back(p->next->next); 32 push_heap(minHeap.begin(),minHeap.end(),greater); 33 p=p->next; 34 } 35 return head.next; 36 } 37 private: 38 static bool greater(ListNode* l1,ListNode* l2){ 39 if(l1 == nullptr) return true; 40 else if(l2 == nullptr) return false; 41 else return l1->val >= l2->val; 42 } 43 }; 44 45 int main() 46 { 47 vector<ListNode*> lists; 48 ListNode* list1 = new ListNode(1); 49 list1->next = new ListNode(3); 50 list1->next->next = new ListNode(6); 51 52 ListNode* list2 = new ListNode(2); 53 list2->next = new ListNode(4); 54 list2->next->next = new ListNode(5); 55 56 ListNode* list3 = new ListNode(100); 57 58 lists.push_back(list1); 59 lists.push_back(list2); 60 lists.push_back(list3); 61 62 Solution s; 63 ListNode *head; 64 head = s.mergeKLists(lists); 65 while(head!= nullptr) 66 { 67 std::cout << head->val << "->"; 68 head = head->next; 69 } 70 return 0; 71 }
标签:
原文地址:http://www.cnblogs.com/wxquare/p/4901248.html