题目描述
合并k个已排序的链表并将其作为一个已排序的链表返回。分析并描述其复杂度。
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:合并k路有序链表,可以用最小堆,然后每次送入堆中,取出最小的,并将该链表下一值取出放入
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: static bool cmp(const ListNode *l1, const ListNode *l2) { return l1->val<l2->val; } ListNode *mergeKLists(vector<ListNode *> &lists) { int n = lists.size(); ListNode *res = new ListNode(-1); if (n<1) return res->next; if (n<2) return lists[0]; ListNode *p = res; int m = 0; for(int i=0;i<n;++i) { if(lists[i]==NULL) { swap(lists[m],lists[i]); m++; } } while(m < n-1) { sort(lists.begin()+m,lists.end(),cmp); p->next=lists[m]; p=p->next; lists[m]=lists[m]->next; if(lists[m]==NULL) { m++; } } if(lists[m]!=NULL) p->next=lists[m]; return res->next; } };