Sort 排序

21. Merge Two Sorted Lists

  • DummyNode的使用
class Solution(object):
    def mergeTwoLists(self, l1, l2):
        dummyNode = ListNode(-1)
        cur = dummyNode
        while l1 and l2:
            if l1.val < l2.val:
                cur.next = l1
                l1 = l1.next
            else:
                cur.next = l2
                l2 = l2.next
            cur = cur.next
        cur.next = l1 if l1 else l2
        return dummyNode.next

23. Merge k Sorted Lists

  • Heap
class Solution(object):
    def mergeKLists(self, lists):
        cur = dummyNode = ListNode(0)
        heap = []
        for node in lists:
            if node:
                heapq.heappush(heap, (node.val, node))

        while heap:
            val, node = heapq.heappop(heap)
            cur.next = node
            if node.next:
                heapq.heappush(heap, (node.next.val, node.next))
            cur = cur.next
        return dummyNode.next

results matching ""

    No results matching ""