leetcode 23: Merge k ordered linked lists

Title: Merge k ordered linked lists

  • Title description:
    Merge k sorted linked lists and return the merged sorted linked list. Please analyze and describe the complexity of the algorithm.

  • Example:

    Input:
    [
    1->4->5,
    1->3->4,
    2->6
    ]
    Output: 1->1->2->3->4->4->5->6

Divide and conquer thinking:

/**
 * 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) {
       if(lists.size()==0){  //如果lists为空,返回NULL
           return NULL;
       }
        if(lists.size() == 1){
            return lists[0];  //如果只有一个lists,直接返回头指针
        }
        if(lists.size()==2){  //如果有两个lists,调用两个list merge函数
            return mergeTwoLists(lists[0],lists[1]);
        }
        int mid = lists.size()/2;
        std::vector<ListNode*> sub1_lists;
        std::vector<ListNode*> sub2_lists;  //拆分lists为两个字lists
        for(int i =0;i<mid;i++){
            sub1_lists.push_back(lists[i]);
        }
        for(int i = mid;i<lists.size();i++){
            sub2_lists.push_back(lists[i]);
        }
        ListNode *l1 = mergeKLists(sub1_lists);
        ListNode *l2 = mergeKLists(sub2_lists);
        return mergeTwoLists(l1,l2);  //分治处理
    }
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1 == nullptr){
            return l2;
        }
        if(l2 == nullptr){
            return l1;
        }
        if(l1->val <= l2->val){
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        }
        else{
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};

Sorting Ideas:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#include <vector>
#include <algorithm>
bool cmp(const ListNode *a,const ListNode *b){
    return a->val < b->val;
}
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        std::vector<ListNode *> node_vec;
        for(int i = 0;i<lists.size();i++){
            ListNode *head = lists[i];  //遍历k个链表,将节点全部添加至node_vec
            while(head){
                node_vec.push_back(head);
                 head = head->next;
            }
         }
       if(node_vec.size() == 0){
           return NULL;
       }
    std::sort(node_vec.begin(),node_vec.end(),cmp);  //根据节点数值进行排序
    for(int i = 1;i<node_vec.size();i++){  //连接新的链表
        node_vec[i-1]->next = node_vec[i];
    }
    node_vec[node_vec.size()-1]->next = NULL;
    return node_vec[0];
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325983447&siteId=291194637