23. Merge k Sorted Lists

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

AC代码:

def mergeKLists_merge_sort(self, lists):
        def merge(lst1, lst2):
            dummy = pt = ListNode(-1)
            while lst1 and lst2:
                if lst1.val < lst2.val:
                    pt.next = lst1
                    lst1 = lst1.next
                else:
                    pt.next = lst2
                    lst2 = lst2.next
                pt = pt.next

            pt.next = lst1 if not lst2 else lst2
            return dummy.next
        if not lists:
            return None
        if len(lists) == 1:
            return lists[0]
        mid = len(lists)/2
        left = self.mergeKLists_merge_sort(lists[:mid])
        right = self.mergeKLists_merge_sort(lists[mid:])
        return merge(left, right)

开始用的递归,发现超时了。后来借鉴了网上的代码,用的是归并排序。

此外还有优先级队列等方法,后面补充。

你可能感兴趣的:(23. Merge k Sorted Lists)