第二周Merge k Sorted Lists

本文深入解析了LeetCode上第23题“合并K个有序链表”的算法实现,采用分治策略将多个有序链表高效合并为一个。详细介绍了算法步骤,包括如何将链表分组、递归排序以及最终合并链表的过程。

Merge k Sorted Lists

本周讲的是分治,所以选的题目也是分治的问题
LeetCode上的23题:https://leetcode.com/problems/merge-k-sorted-lists/description/

题目

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

Example:

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

题解

分:当要排序的链表大于2时,将链表分成左右两个部分排序,若要排序的链表数为一时,拷贝该链表并返回
治:对两个已排序链表进行排序,返回包含两个链表元素的已排序链表

代码

class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0) return NULL;
        return _mergeKlists(lists, 0, lists.size() - 1);
    }

    ListNode* _mergeKlists(vector<ListNode*>& lists, int left, int right) {
        ListNode* newList = new ListNode(0);
        ListNode* cur = newList;

        if (left == right) {
            ListNode* p = lists[left];
            while (p != NULL) {
                cur->next = new ListNode(p->val);
                p = p->next;
                cur = cur->next;
            }
        }
        else {
            int mid = (left + right) / 2;
            ListNode* l = _mergeKlists(lists, left, mid);
            ListNode* r = _mergeKlists(lists, mid + 1, right);
            while (l != NULL && r != NULL) {
                if (l->val < r->val) {
                    cur->next = l;
                    l = l->next;
                }
                else {
                    cur->next = r;
                    r = r->next;
                }
                cur = cur->next;
            }
            if (l == NULL) {
                cur->next = r;
            }
            else {
                cur->next = l;
            }
        }

        cur = newList->next;
        delete newList;
        return cur;
    }
};

分析

算法将多个排序链表分成两个部分,最后将两个已排序链表合并成一个排序链表,令N为节点总数,k为链表总数。
则算法会经过log2(k)次分治,每次合并链表的时间复杂度为O(N),故总时间为O(log2(k) * N).

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

余额充值