My Python recursive solution without using priority queue

  • 0

    Based on merging two sorted lists; divide and conquer. Below is the complete code:

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

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.