题目:
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) { if (lists.size()==0) return NULL; return Solution::mergeK(lists, 0, lists.size()-1); } static ListNode* mergeK(vector<ListNode*>& lists, int begin, int end ) { if ( begin==end ) return lists[begin]; if ( (begin+1)==end ) return Solution::mergeTwo(lists[begin], lists[end]); int mid = ( begin + end ) / 2; ListNode *firstHalf = Solution::mergeK(lists, begin, mid); ListNode *secondHalf = Solution::mergeK(lists, mid+1, end); return Solution::mergeTwo(firstHalf, secondHalf); } static ListNode* mergeTwo( ListNode *h1, ListNode *h2 ) { ListNode dummy(-1); ListNode *p = &dummy; while ( h1 && h2 ){ if ( h1->val<h2->val ){ p->next = h1; h1 = h1->next; } else{ p->next = h2; h2 = h2->next; } p = p->next; } p->next = h1 ? h1 : h2; return dummy.next; } };
tips:
多路归并写法。
时间: 2024-10-25 11:49:44