合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:[ 1->4->5, 1->3->4, 2->6 ]输出: 1->1->2->3->4->4->5->6# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None import heapq class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: h = [] for node in lists: while node: h.append(node.val) node = node.next if not h: return None heapq.heapify(h) #转换成最小堆 # 构造链表 root = ListNode(heapq.heappop(h)) curnode = root while h: nextnode = ListNode(heapq.heappop(h)) curnode.next = nextnode curnode = nextnode return root
执行用时 : 104 ms, 在Merge k Sorted Lists的Python3提交中击败了77.24% 的用户
内存消耗 : 17.2 MB, 在Merge k Sorted Lists的Python3提交中击败了42.33% 的用户
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。