Merge k Sorted Lists

本文介绍了一种高效算法,用于合并多个已排序的链表为一个有序链表。通过使用优先队列来选取最小元素并保持整体有序性,该算法的时间复杂度为O(k*n*log(k)),空间复杂度为O(k)。

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

pro:将k个排好序的链表merge成一个有序链表,分析其复杂度

sol:

1.定义一个struct记录某个结点对应的链表的id,定义一个优先队列,每次将所有的链表表头和id信息入队列,O(log(k))的时间取出最小值。

2.将队首加到结果链表中,对应链表后移,如果没到链尾,加入。队列不为空的时候要继续这个操作。

每个节点都是如此添加到结果链表中的,因此时间复杂度是O(k*n*(log(k))),空间复杂度是优先队列的空间复杂度,O(k),在构造结果链表时不需要额外的空间的,这个代码里有用到,下次要优化。

code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
 
 struct node//记录了一个节点对应的是哪个链表
 {
     int index;
     ListNode *listnode;
     node(int index,ListNode *ll):index(index),listnode(ll){}
 };
 struct cmp
 {
     bool operator()(node* bb,node* cc)
     {
         return bb->listnode->val>cc->listnode->val;
     }
 };
 
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists)
    {
        priority_queue< node*,vector<node*>,cmp > myque;//定义优先队列
        while(!myque.empty())
            myque.pop();
        int i;
        ListNode *res = new ListNode(0);
        ListNode *cur = res;
        for(i=0;i<lists.size();i++)//将所有的表头插入到优先队列中
        {
            if(lists[i]!=NULL)
            {
                node* temp = new node(i,lists[i]);
                myque.push(temp);
            }
        }
        while(!myque.empty())//一直
        {
            node *ttop = myque.top();//找优先队列的队头
            res->next = ttop->listnode;
            res = res->next;
            myque.pop();
            if(lists[ttop->index]->next!=NULL)//如果这条链表没到最后的话
            {
                node *tt = new node(ttop->index,lists[ttop->index]->next);
                lists[ttop->index] = lists[ttop->index]->next;//将选中的链表的表头后移
                myque.push(tt);//并且选中链表的后面一个节点入队列
            }
        }
        return cur->next;
    }
};


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、付费专栏及课程。

余额充值