LeetCode 23. Merge k Sorted Lists

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {//用递归去做更好
        if (lists == null || lists.length == 0) return null;
        PriorityQueue<ListNode> queue = new PriorityQueue<>(lists.length, (a, b) -> a.val - b.val);//this compare method means the linkedlist who has the smallest head node will be polled first every time.
        ListNode dummy = new ListNode(0);
        ListNode cur = dummy;

        for (ListNode list : lists) {
            if (list != null) {
                queue.add(list);//将lists所有元素都添加到PQ
            }
        }
        while (!queue.isEmpty()) {//这一段代码可真是太秀了
            cur.next = queue.poll();//poll出来
            cur = cur.next;//就添加了一个
            if (cur.next != null) {
                queue.add(cur.next);//把剩下的放回去
            }//everytime, we get the least lomg linkedlist's first node to dummy linkedlist
        }
        return dummy.next;
    }
}

除了上面的方法之外 我们还可以meger with divide and conquer.

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        amount = len(lists)
        interval = 1
        while interval < amount:
            for i in range(0, amount - interval, interval * 2):
                lists[i] = self.merge2Lists(lists[i], lists[i + interval])
            interval *= 2
        return lists[0] if amount > 0 else None

    def merge2Lists(self, l1, l2):
        head = point = ListNode(0)
        while l1 and l2:
            if l1.val <= l2.val:
                point.next = l1
                l1 = l1.next
            else:
                point.next = l2
                l2 = l1
                l1 = point.next.next
            point = point.next
        if not l1:
            point.next=l2
        else:
            point.next=l1
        return head.next
posted @ 2020-11-20 03:28  EvanMeetTheWorld  阅读(19)  评论(0)    收藏  举报