Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { // Start typing your C/C++ solution below // DO NOT write int main() function if(lists.size()==0)return NULL; int min,index; int i=0; for(;i<lists.size();i++){ if(lists[i]!=NULL){ min=lists[i]->val; index=i; break; } } if(i==lists.size())return NULL; i++; if(i<lists.size()) for(;i<lists.size();i++){ if(lists[i]!=NULL&&lists[i]->val<min){ min=lists[i]->val; index=i; } } ListNode* root=lists[index]; lists[index]=lists[index]->next; ListNode* tail=root; while(true){ int i=0; for(;i<lists.size();i++){ if(lists[i]!=NULL){ min=lists[i]->val; index=i; break; } } if(i==lists.size())return root; i++; if(i<lists.size()) for(;i<lists.size();i++){ if(lists[i]!=NULL&&lists[i]->val<min){ min=lists[i]->val; index=i; } } tail->next=lists[index]; tail=tail->next; lists[index]=lists[index]->next; } } };