1. 程式人生 > >python leetcode 23. Merge k Sorted Lists

python leetcode 23. Merge k Sorted Lists

Merge two Sorted Lists的進階版

建立Merge two Sorted Lists函式 合併兩個連結串列,mergeKLists中不斷二分再合併

class Solution(object):
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        if not lists:
            return None
        if len(lists)
== 1: return lists[0] l1 = self.mergeKLists(lists[:len(lists)//2]) l2 = self.mergeKLists(lists[len(lists)//2:]) head = self.mergeTwoLists(l1,l2) return head def mergeTwoLists(self, l1, l2): if not l1 and not l2: return None if not
l1: return l2 if not l2: return l1 p = ListNode(0) res = p while l1 and l2: if l1.val < l2.val: p.next = l1 l1=l1.next p = p.next else: p.next = l2 l2 =
l2.next p = p.next if l1: p.next=l1 if l2: p.next=l2 return res.next