这篇“c++如何合并K个排序链表”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“c++如何合并K个排序链表”文章吧。
合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
示例:
输入:[ 1->4->5, 1->3->4, 2->6]输出: 1->1->2->3->4->4->5->6
# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = Noneclass Solution(object): def mergeKLists(self, lists): """ :type lists: List[ListNode] :rtype: ListNode """ #合成一个大的listlist然后排序 lists = [x for x in lists if x] if not lists or all([not x for x in lists]): return head = lists.pop() curr = head while curr.next: curr = curr.next while lists: tmp = lists.pop() curr.next = tmp while tmp.next: tmp = tmp.next curr = tmp if not head or not head.next: return head return self.mergeSort(head) def mergeSort(self, head): if not head.next: return head pre, slow, fast = None, head, head while fast and fast.next: prev, slow, fast = slow, slow.next, fast.next.next prev.next = None left = self.mergeSort(head) right = self.mergeSort(slow) return self.merge(left, right) def merge(self, left, right): if not left: return right if not right: return left if left.val < right.val: res = left res.next = self.merge(left.next, right) else: res = right res.next = self.merge(left, right.next) return res
以上就是关于“c++如何合并K个排序链表”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注编程网行业资讯频道。