My Python recursive solution without using priority queue


  • 0
    J

    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:
                    temp.next = l1
                    l1 = l1.next
                else:
                    temp.next = l2
                    l2 = l2.next
                temp = temp.next
            if l1:
                temp.next = l1
            if l2:
                temp.next = l2
            return head.next
            
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
            if not lists:
                return None
            
            k = len(lists)
            
            if k == 1:
                return lists[0]
            else:
                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.