23. Merge k Sorted Lists

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists

23. Merge k Sorted Lists