day6--Merge k sorted linked lists

divide and conquer

Divide the k linked lists into two groups, merge them recursively, and finally merge the two merged linked lists into one.

The time complexity is O(Nlogk), where N is the total number of nodes in all linked lists and k is the number of linked lists.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <cstddef>
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        int k=lists.size(); 
        if(k==0) return NULL;
        if(k==1) return lists[0];
        int mid=k/2;
        vector<ListNode *> left, right;
        //分成两半
        for(int i=0; i<mid; i++) left.push_back(lists[i]);
        for(int i=mid; i<k; i++) right.push_back(lists[i]);
        ListNode *l1, *l2;
        l1=mergeKLists(left); //左边继续分
        l2=mergeKLists(right); //同理右边
        return merge2Lists(l1, l2); //递归回来即两两合并
    }
    ListNode *merge2Lists(ListNode *l1, ListNode *l2) {//合并两个有序链表(递归的方法)
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
        if(l1->val<l2->val){
            l1->next=merge2Lists(l1->next, l2);
            return l1;
        }else{
            l2->next=merge2Lists(l1, l2->next);
            return l2;
        }
    }
};

Guess you like

Origin blog.csdn.net/qq_54809548/article/details/130862590