leecode第二十三题(合并K个排序链表)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==NULL)//判断有一组为空的情况
            return l2;
        if(l2==NULL)
            return l1;
        
        if(l1->val>l2->val)//由于我设计的算法问题,需要明确知道第一个值谁小,不妨用l1小,若不满足,就倒一下
            return mergeTwoLists(l2,l1);
        ListNode* res=l1;//保存头指针,留待返回
        while(l2!=NULL)
        {
            while(l1->next!=NULL && l1->next->val<=l2->val)//直到找出l1下一个比当前l2值大的数,且不能为空
                l1=l1->next;
            if(l1->next==NULL)//只要额外判断l1下个为空的情况,这个值肯定不会比l2大
            {
                l1->next=l2;
                break;
            }
            ListNode* l2_next=l2->next;//一定要记住当前l2的下个节点
            l2->next=l1->next;//这里一定要画图,特清晰,不画要崩溃
            l1->next=l2;//注意这里l1指针停在新加入的节点处
            l1=l1->next;
            l2=l2_next;//即便l2为空也不要紧啊
        }
        
        return res;
    }
    
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        int len=lists.size();
        if(len==0)//提前写好三种情况,都是个数的最小单位了
            return NULL;
        if(len==1)
            return lists[0];
        if(len==2)
            return mergeTwoLists(lists[0],lists[1]);
        
        vector<ListNode*> list1(len/2+1);//然后分半,防止有奇数,所以下面是len-len/2-1长度
        vector<ListNode*> list2(len-len/2-1);
        int i=0;
        for(;i<len/2+1;i++)
            list1[i]=lists[i];
        for(;i<len;i++)
            list2[i-len/2-1]=lists[i];//划分好后
        
        ListNode* mer1=mergeKLists(list1);//受归并排序的提示,采用递归实现
        ListNode* mer2=mergeKLists(list2);
        
        return mergeTwoLists(mer1,mer2);
    }
};

分析:

结合之前的写好的两个排序的思想,这个几乎没有阻碍就写出来了,但是明显写的慢,对vector没有python的切片这种都不太清晰,明显经验不足。

但是这个题给我提示,还是要画图,分析又快又好,关键是能验证你的想法能不能行。

而且,一个困难的问题,可以拆成多了小题解决,比如这个,分为递归归并策略和两个排序链表连接,特别有效果。

有点小开心的是时间击败了35%,哦对了,这个时间复杂度平均情况我有点不太清楚,但最坏情况是O(max(n)*m*log(m)),n是m个链表的长度。

原文地址:https://www.cnblogs.com/CJT-blog/p/10584675.html