Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
Example:
Input:
[1->4->5,1->3->4,2->6
]
Output: 1->1->2->3->4->4->5->6
思路:暴力解法,遍历一遍链表把数值存到数组里,排序数组,再把数组整合成链表。
C++ (Brute Force)
class Solution {
public:ListNode* mergeKLists(vector<ListNode*>& lists) { vector<int> v;for(int i&#61;0;i<lists.size();i&#43;&#43;){while(lists[i] !&#61; nullptr ){v.push_back(lists[i]->val);lists[i] &#61; lists[i]->next;}}sort(v.begin(),v.end());ListNode dummy(0);ListNode* curNode &#61; &dummy;for(int i&#61;0;i<v.size();i&#43;&#43;){ListNode* temp &#61; new ListNode(v[i]);curNode->next &#61; temp;curNode &#61; curNode->next;}return dummy.next;}
};