原题地址:https://leetcode.com/problems/merge-k-sorted-lists/description/
题目描述
23.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* merge(vector<ListNode*>& lists, int index1,int index2){
if(lists[index1]==NULL && lists[index2]==NULL){
return NULL;
}
if(lists[index1]==NULL){
return lists[index2];
}
if(lists[index2]==NULL){
return lists[index1];
}
ListNode * temp1 = lists[index1];
ListNode * temp2 = lists[index2];
ListNode * head;
if(temp1->val > temp2->val){
head = temp2;
temp2=temp2->next;
}else{
head = temp1;
temp1= temp1->next;
}
ListNode * current = head;
while(temp1!=NULL && temp2 !=NULL){
if(temp1->val > temp2-> val){
current->next = temp2;
current = current->next;
temp2 = temp2->next;
}else{
current->next = temp1;
current = current->next;
temp1 = temp1->next;
}
}
if(temp1!=NULL){
current->next = temp1;
}else{//temp2!=NULL
current->next = temp2;
}
return head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty()){
return NULL;
}
if(lists.size()==1){
return lists[0];
}
vector<ListNode*> new_lists;
for(int i =0;i<lists.size();){
ListNode * temp;
if(i+1<lists.size()){
temp = merge(lists,i,i+1);
}else{
temp = lists[i];
}
new_lists.push_back(temp);
i+=2;
}
return mergeKLists(new_lists);
}
};
踩坑
提交过程中有几次TLE
和Runtime Error
,TLE是因为merge
函数里指针没处理好(赋值给head
之后没有把temp
移动到下一个元素,不过具体的情况我还是没想象清楚,先留着),RuntimeError
是因为测试的例子里有的list是空的或者整个vector是空的没考虑到。