题目:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input: [ 1->4->5, 1->3->4, 2->6 ] Output: 1->1->2->3->4->4->5->6
思路:
k路归并。找出每次找出所有序列第一个元素中的最小值。
代码:C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<limit.h>
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
vector<ListNode*> list(lists.size());
for(int i = 0; i < list.size(); i++){
list[i] = lists[i];
}
ListNode* head = new ListNode(-1);
ListNode* n = head;
while(1){
int min = INT_MAX;
int index = -1;
for(int i = 0; i < list.size(); i++){
if(list[i] == NULL) continue;
if(list[i] -> val < min){
min = list[i] -> val;
index = i;
}
}
if(index == -1) break;
else{
n -> next = new ListNode(list[index] -> val);
list[index] = list[index] -> next;
n = n -> next;
}
}
ListNode* temp = head -> next;
delete head;
return temp;
}
};
改进:leetcode官方 https://leetcode.com/problems/merge-k-sorted-lists/solution/