23.合并K个升序链表

23.合并K个升序链表_第1张图片
我的思路是先写个两两归并得函数,这个之前有个题就写过了,21.合并两个有序链表(优化了下,原地归并),然后把这个参数链表当作队列(我的顺序是前进后出),先拿出后面两个链表,归并之后插到队首,直到参数链表中只有一个链表的时候返回第一个链表就行。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        
        def mergeTwoLists(list1, list2):
            if not list1: return list2
            if not list2: return list1

            ptr1 = list1
            ptr2 = list2
            dummy = ListNode()
            pre = dummy
            while ptr1 and ptr2:
                if ptr1.val < ptr2.val:
                    pre.next = ptr1
                    pre = ptr1
                    ptr1 = ptr1.next
                else: 
                    pre.next = ptr2
                    pre = ptr2
                    ptr2 = ptr2.next

            if not ptr1: pre.next = ptr2
            if not ptr2: pre.next = ptr1
            return dummy.next 
               
        if len(lists) == 0:return None
        if len(lists) == 1:lists[0]

        while len(lists) != 1:
            list1 = lists.pop()
            list2 = lists.pop()
            list3 = mergeTwoLists(list1, list2)
            lists.insert(0, list3)
        
        return lists[0]

参考链接1python-23合并K个升序链表-两两合并、归并、最小堆

  • 二分法来归并
def mergeSort(self, lists: List[ListNode], l: int, r: int) -> ListNode:
        if l == r:
            return lists[l]
        m = (l + r) // 2
        L = self.mergeSort(lists, l, m) #循环的递归部分
        R = self.mergeSort(lists, m + 1, r)
        return self.mergeTwoLists(L, R) #调用两链表合并函数

参考链接2【python3】合并K个升序链表

  • 利用python库的小根堆提高效率
class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        heap = []
        for i in lists:
            while i:
                heapq.heappush(heap,i.val)
                i = i.next

        d = c = ListNode(-1)
        while heap:
            c.next = ListNode(heapq.heappop(heap))
            c = c.next
        return d.next

你可能感兴趣的:(链表,数据结构,leetcode)