Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
=======
合并k个链表形成一个已排序链表
思路:
如何合并两个有序链表?经典merge算法:
ListNode *mergeList(ListNode *head1,ListNode *head2){ ListNode dummy(-1); ListNode *h = &dummy; while(head1 && head2){ if(head1->val <= head2->val){ h->next = head1; head1 = head1->next; }else{ h->next = head2; head2 = head2->next; } h = h->next; } if(head1) h->next = head1; if(head2) h->next = head2; return dummy.next; }
对vector中的链表依次merge
ListNode* mergeKLists(vector<ListNode*>& lists) { /// if(lists.empty()) return nullptr; ListNode *p = lists[0]; for(int i = 1;i<(int)lists.size();i++){ p = mergeList(p,lists[i]); } return p; }
=======
这个算法有点问题:会有大量重复的计算,比如vector[0]中的链表就会被merge ( vector.size()-1)次
可以按照k路merge的思路,做一边.