Merge k Sorted Lists
Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
根据k个已经排好序的链表构造一个排序的链表,采用类似归并排序的算法可以通过测试
/** * 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.empty()) return nullptr; return helper(lists, 0 , lists.size()-1); } private: ListNode* merge(ListNode* left, ListNode* right){ ListNode* head = new ListNode(0); ListNode* last = head; while(left && right){ if(left->val < right->val){ last->next = left; left = left->next; } else{ last->next = right; right = right->next; } last = last->next; } last->next = (left==nullptr)? right: left; return head->next; } ListNode* helper(vector<ListNode*>& lists, int start, int end){ cout << start << " "<<end <<endl; if(start == end) return lists[start]; else if (start+1 ==end){ return merge(lists[start], lists[end]); } ListNode* left = helper(lists, start, start+(end-start)/2); ListNode* right = helper(lists, start + (end - start) / 2 + 1, end); return merge(left,right); } };