Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
时间复杂度:O(nlogk),合并k个链表,总共n个元素.(考察多路归并)
class Solution { //小->大
public:
void keepHeap(vector<ListNode*>&vec,int i,int n){
int le = 2*i;
int ri = 2*i+1;
int min = i;
if (le<n && vec[min]->val>vec[le]->val) min = le;
if (ri<n && vec[min]->val>vec[ri]->val) min = ri;
if (min!=i) {
swap(vec[i],vec[min]);
keepHeap(vec,min,n);
}
}
void buildHeap(vector<ListNode*>&vec) {
int len = vec.size();
for (int i=len/2; i>=0; --i)
keepHeap(vec,i,len);
}
ListNode *mergeKLists(vector<ListNode *> &lists) {
int len = lists.size();
if (len<1) return NULL;
if (len==1) return lists[0];
vector<ListNode*> vec;
for(int i=0; i<len;++i){
if (!lists[i]) continue;
vec.push_back(lists[i]);
}
len = vec.size();
if (len<1) return NULL;
if (len ==1) return vec[0];
buildHeap(vec);
ListNode *head,*cur;
head = cur = vec[0];
while (len){
if (!vec[0]->next){
vec[0]=vec[--len];
keepHeap(vec,0,len);
} else{
vec[0] = vec[0]->next;
keepHeap(vec,0,len);
}
cur->next = vec[0];
cur = cur->next;
}
cur->next=NULL;
return head;
}
};