(力扣记录)23. 合并K个升序链表

发布时间:2024年01月20日

数据类型:链表

时间复杂度:O(NK logK),?N为链表长度

空间复杂度:O(K)

代码实现:

# 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]:
        if len(lists) == 0: return None

        while len(lists) > 1:
            merged = []
            for i in range(0, len(lists), 2):
                l1 = lists[i]
                l2 = lists[i + 1] if i + 1 < len(lists) else None
                merged.append(self.merge(l1, l2))
            lists = merged
        return lists[0]

    def merge(self, l1, l2):
        curr = out = ListNode()
        while l1 and l2:
            if l1.val < l2.val:
                curr.next = l1
                l1 = l1.next
            else:
                curr.next = l2
                l2 = l2.next
            curr = curr.next

        if l1 or l2:
            if l1:
                curr.next = l1
            else:
                curr.next = l2

        return out.next

文章来源:https://blog.csdn.net/Wilson_Lin_01/article/details/135709723
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。