题目leetcode23 Merge k Sorted Lists
难度等级:hard
思路
就是多路归并,注意判断某一路为空时候的处理就可以了
实现
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
int k = lists.size();
if(k == 0) return NULL;
ListNode * ret = NULL, * copy = NULL, * current[k];
for(int i = 0; i < k; i++){
current[i] = lists[i];
}
bool first = true;
while(true) {
// choose the smallest one
int min = 2147483647, index = -1;
for(int i = 0; i < k; i++)
if(current[i] != NULL && current[i]->val <= min){
min = current[i]->val;
index = i;
}
if(index == -1)
break;
current[index] = current[index]->next;
if(first) {
ret = new ListNode(min);
copy = ret;
first = false;
} else {
copy->next = new ListNode(min);
copy = copy->next;
}
}
return ret;
}
};