Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
题目大意:合并k个有序链表并分析时间复杂度。
解题思路:每两个链表进行一次合并,再对合并好的链表重复上述过程。k个链表需要合并O(k)次,每次合并需要O(n)的时间,所以总的时间复杂度为O(kn)。
代码如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2) {
struct ListNode *head = NULL;
struct ListNode **now = &head;
struct ListNode *ptr1 = l1;
struct ListNode *ptr2 = l2;
while(ptr1 && ptr2){
if(ptr1->val < ptr2->val){
*now = ptr1;
ptr1 = ptr1->next;
}else{
*now = ptr2;
ptr2 = ptr2->next;
}
now = &(*now)->next;
}
if(ptr1) *now = ptr1;
if(ptr2) *now = ptr2;
return head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
int begin = 0, end = listsSize - 1;
while(end > 0){
for(begin = 0;begin < end;end--,begin++){
lists[begin] = mergeTwoLists(lists[begin],lists[end]);
}
}
return lists[0];
}