23. Merge k Sorted Lists

本文详细介绍了如何使用最小堆构建优先队列来合并k个已排序的链表,并返回单一排序的链表。通过遍历输入数组,将非空表头节点加入最小堆,每次从堆中取出最小值作为结果,之后加入取出节点的下一个非空节点。最后,当最小堆为空时结束操作。该方法的时间复杂度为O(nlogn),空间复杂度为O(m),其中m为输入数组的长度。

题目:

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

链接: http://leetcode.com/problems/merge-k-sorted-lists/

题解:

使用min heap构建的priority queue, 遍历输入数组,将非空表头节点加入min PQ,每次从PQ中poll()出最小值作为当前结果,之后加入取出节点的下一个非空节点。 当min PQ为空时结束。

Time Complexity - O(nlogn), Space Complexity - O(m), m为输入数组的length

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) { // using priority queue (min heap)
        if(lists == null || lists.length == 0)
            return null;
        PriorityQueue<ListNode> minPQ = new PriorityQueue<ListNode>(lists.length, 
            new Comparator<ListNode>(){
                public int compare(ListNode a, ListNode b) {
                    if(a.val < b.val)
                        return -1;
                    else if(a.val > b.val)
                        return 1;
                    else
                        return 0;
                }
            });
        
        for(ListNode node : lists) {
            if(node != null)
                minPQ.offer(node);
        }
            
        
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        
        while(minPQ.size() > 0) {
            ListNode tmp = minPQ.poll();
            node.next = tmp;
            if(tmp.next != null)
                minPQ.offer(tmp.next);
            node = node.next;
        }
        
        return dummy.next;
    }
}

 

二刷:

Java:

跟一刷一样,也是先建立一个自带Comparator的min-oriented PriorityQueue。初始把所有非空list head都放进pq, 之后poll出当前最小的值设置为node.next,假如这条list非空,则将其之后的节点作为head放入pq中继续进行比较。这里insert和deleteMin操作复杂度都是O(logk),k是lists.length

Time Complexity - O(nlogk), Space Complexity - O(k),  这里k为lists的长度,  n为所有的节点数

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>(new Comparator<ListNode>() {
            public int compare(ListNode l1, ListNode l2) {
                return l1.val - l2.val;
            }
            });
        for (ListNode head : lists) {
            if (head != null) {
                pq.offer(head);
            }
        }
        while (pq.size() > 0) {
            node.next = pq.poll();
            node = node.next;
            if (node.next != null) {
                pq.offer(node.next);
            }
        }
        return dummy.next;
    }
}

 

下面是把匿名Comparator换成了使用了Lambda expression, 但是巨慢无比。可能JVM还没有很好的优化。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        ListNode dummy = new ListNode(-1);
        ListNode node = dummy;
        PriorityQueue<ListNode> pq = new PriorityQueue<ListNode>((ListNode l1, ListNode l2) -> l1.val - l2.val);
        for (ListNode head : lists) {
            if (head != null) {
                pq.offer(head);
            }
        }
        while (pq.size() > 0) {
            node.next = pq.poll();
            node = node.next;
            if (node.next != null) {
                pq.offer(node.next);
            }
            node.next = null;
        }
        return dummy.next;
    }
}

 

Python:

还是不熟悉Python,好难写,多参考了cbmbbz,放了tuple在pq里。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
from Queue import PriorityQueue

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        dummy = ListNode(None)
        node = dummy
        pq = PriorityQueue();
        for head in lists:
            if head:
                pq.put((head.val, head))
        while pq.qsize() > 0:
            node.next = pq.get()[1]
            node = node.next
            if node.next:
                pq.put((node.next.val, node.next))
        return dummy.next
        

 

需要继续学习heap的原理,heapify - swim up or sink down,bionomial heap等等。

Reference:

https://leetcode.com/discuss/9279/a-java-solution-based-on-priority-queue

http://algs4.cs.princeton.edu/24pq/

https://leetcode.com/discuss/78758/10-line-python-solution-with-priority-queue

https://leetcode.com/discuss/55662/108ms-python-solution-with-heapq-and-avoid-changing-heap-size

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

余额充值