Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

思路:开始做过两两合并的链表,此时做k路合并,即将k个链表进行合并,可以先将这k个链表进行两两合并,知道合并为一个链表。直接调用前面写过的两两合并的例子。

 

C++代码实现:

#include<iostream>
#include<new>
#include<vector>
using namespace std;

//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.empty())
            return NULL;
        if(lists.size()==1)
            return lists[0];
        int i;
        vector<ListNode *> temp=lists;
        while(lists.size()!=1)
        {
            temp=lists;
            lists.clear();
            for(i=0; i<(int)temp.size(); i=i+2)
            {
                ListNode *L=NULL;
                if(i+1<int(temp.size()))
                    L=mergeTwoLists(temp[i],temp[i+1]); //直接调用将两个链表合并
                else
                    L=temp[i]; //如果有奇数个链表,直接将最后一个加入vector中。
                lists.push_back(L);
            }
        }
        return lists[0];
    }
  //下面是两两合并的链表 ListNode
*mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode *p=NULL; //q始终记录l2中的元素,qq是取出来要插入到l1中的元素 ListNode *q=NULL; ListNode *qq=NULL; //pre是p的前驱,插入比p小的元素时需要 ListNode *pre=NULL; if(l1&&l2) { pre=p=l1; qq=q=l2; while(p&&q) { if(p->val<=q->val) { pre=p; p=p->next; } else { qq=q; q=q->next; if(l1==p) { qq->next=l1; l1=qq; pre=p=l1; continue; } qq->next=p; pre->next=qq; pre=qq; } } while(q) { pre->next=q; pre=q; q=q->next; } } if(l1==NULL) l1=l2; return l1; } void createList(ListNode *&head,int *arr) { ListNode *p=NULL; int i=0; for(i=0; i<5; i++) { if(head==NULL) { head=new ListNode(arr[i]); if(head==NULL) return; } else { p=new ListNode(arr[i]); p->next=head; head=p; } } } }; int main() { Solution s; ListNode *L1=NULL; ListNode *L2=NULL; ListNode *L3=NULL; ListNode *L=NULL; int arr1[5]= {11,9,7,5,3}; int arr2[5]= {10,8,6,4,2}; int arr3[5]={14,13,12,1,0}; s.createList(L1,arr1); s.createList(L2,arr2); s.createList(L3,arr3); vector<ListNode *> lists={L1,L2,L3}; L=s.mergeKLists(lists); while(L) { cout<<L->val<<" "; L=L->next; } }

运行结果:

//不需要使用临时空间,每次直接将合并之后的两个链表从lists中删除,兩两合并后的结果插入到list的结尾
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        if(lists.empty())
            return NULL;
        if(lists.size()==1)
            return lists[0];
        ListNode *L=NULL;
        while(lists.size()!=1)
        {
            auto iter=lists.begin();
            ListNode *first=*iter;
            lists.erase(iter);
            iter=lists.begin();
            ListNode *second=*iter;
            lists.erase(iter);
            L=mergeTwoLists(first,second);
            lists.push_back(L);
        }
        return lists[0];
    }
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(l1==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        ListNode *head=NULL;
        ListNode *r=NULL;
        ListNode *p=l1;
        ListNode *q=l2;
        if(p->val<q->val)
        {
            head=p;
            r=head;
            p=p->next;
        }
        else
        {
            head=q;
            r=head;
            q=q->next;
        }
        r->next=NULL;
        while(p&&q)
        {
            if(p->val<q->val)
            {
                r->next=p;
                r=p;
                p=p->next;
            }
            else
            {
                r->next=q;
                r=q;
                q=q->next;
            }
            r->next=NULL;
        }
        if(q)
            p=q;
        r->next=p;
        return head;
    }
};

 

To merge k sorted linked lists, one approach is to repeatedly merge two of the linked lists until all k lists have been merged into one. We can use a priority queue to keep track of the minimum element across all k linked lists at any given time. Here's the code to implement this idea: ``` struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; // Custom comparator for the priority queue struct CompareNode { bool operator()(const ListNode* node1, const ListNode* node2) const { return node1->val > node2->val; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<ListNode*, vector<ListNode*>, CompareNode> pq; for (ListNode* list : lists) { if (list) { pq.push(list); } } ListNode* dummy = new ListNode(-1); ListNode* curr = dummy; while (!pq.empty()) { ListNode* node = pq.top(); pq.pop(); curr->next = node; curr = curr->next; if (node->next) { pq.push(node->next); } } return dummy->next; } ``` We start by initializing a priority queue with all the head nodes of the k linked lists. We use a custom comparator that compares the values of two nodes and returns true if the first node's value is less than the second node's value. We then create a dummy node to serve as the head of the merged linked list, and a current node to keep track of the last node in the merged linked list. We repeatedly pop the minimum node from the priority queue and append it to the merged linked list. If the popped node has a next node, we push it onto the priority queue. Once the priority queue is empty, we return the head of the merged linked list. Note that this implementation has a time complexity of O(n log k), where n is the total number of nodes across all k linked lists, and a space complexity of O(k).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值