TLE with Brute Force Method when the list is empty


  • 0
    P

    Here is my Brute Force solution with Python. However, OJ indicated time limit error when the input is [[]]. I was expecting the Brute Force method would exceed the time limit, but definitely not in this case. Is there anything wrong with my code?

    class Solution:
    # @param {ListNode[]} lists
    # @return {ListNode}
    def mergeKLists(self, lists):
        k = len(lists)
        dummy = ListNode(None)
        i = 0
        curr_head = dummy
       # merge the k lists one by one
        while i < k:
            head = dummy
            p = curr_head
            q = lists[i]
            # merge two lists
            while p is not None and q is not None:
                if p.val <= q.val:
                    head.next = p
                    p = p.next
                else:
                    head.next = q
                    q = q.next
                head = head.next
            if p is not None:
                head.next = p
            if q is not None:
                head.next = q
            curr_head = dummy.next
            i += 1
        return dummy.next

Log in to reply
 

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