題目
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路
K 路歸併鏈表;
注意:不能用 ListNode *cur 來記錄當前的鏈表節點(因爲這樣的話無法修改數組中的鏈表),而是要直接在數組中修改鏈表,所以要用 index 記錄要修改的鏈表。
假設所有的節點總數是 Sum, 共有 Num 個鏈表, 時間複雜度是:O(Num*Sum).
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int num = lists.size();
if(num==0) return NULL;
if(num==1) return lists[0];
ListNode *head = NULL;
ListNode *tail = NULL;
int index = -1;
while(true) {
int min = INT_MAX;
index = -1;
for(int i=0;i<num;i++) {
if(lists[i]) {
if(lists[i]->val<min) {
min = lists[i]->val;
index = i;
}
}
}
// There is no extra node to sort
if(index<0)
break;
if(head==NULL)
head = lists[index];
else
tail->next = lists[index];
tail = lists[index];
lists[index] = lists[index]->next;
}
return head;
}
};