LeetCode: MergekSortedLists

时间:2024-01-05 18:53:02

Title:

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

排好序的,然后merge,很容易让人联想到归并排序。可以将k个序列按照二分进行分割,然后当长度为1时返回一个排好序的序列,最后将两个序列merge

class Solution{
public:
ListNode* merge(ListNode* list1, ListNode* list2){
ListNode head(),*tail = &head;
while (list1 != NULL && list2 != NULL){
if (list1->val < list2->val){
tail->next = list1;
tail = list1;
list1 = list1->next;
}else{
tail->next = list2;
tail = list2;
list2 = list2->next;
}
}
if (list1 != NULL){
tail->next = list1;
}
if (list2 != NULL){
tail->next = list2;
}
return head.next;
}
ListNode* divide(int l,int r,vector<ListNode* > &lists){
int m = (l + r) / ;
if (l < r){
return merge(divide(l,m,lists),divide(m+,r,lists));
}else
return lists[l];
}
ListNode* mergeKLists(vector<ListNode* > &lists){
int k = lists.size();
if ( == k)
return NULL;
return divide(,k-,lists);
}
};