请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

正在回答 回答被采纳积分+3

1回答

PegasusWang 2019-03-19 23:24:24
"""
https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
  1->4->5,
  1->3->4,
  2->6
]
Output: 1->1->2->3->4->4->5->6
"""


from heapq import heappop, heapify
# Definition for singly-linked list.


class ListNode:
    def __init__(self, x, next=None):  # 注意我这里next参数
        self.val = x
        self.next = next


class Solution:
    def mergeKLists(self, lists):
        """
        :type lists: List[ListNode]
        :rtype: ListNode
        """
        h = []
        for node in lists:
            while node:
                h.append(node.val)
                node = node.next

        if not h:  # 注意这里的边界值 [[]]
            return None
        heapify(h)   # inplace 建堆
        root = ListNode(heappop(h))
        curnode = root

        while h:
            nextnode = ListNode(heappop(h))
            curnode.next = nextnode

            curnode = nextnode

        return root


def to_list(head):
    """list to []"""
    res = []
    curnode = head
    while curnode:
        res.append(curnode.val)
        curnode = curnode.next
    return res

def test_merge():
    l1 = ListNode(1, ListNode(4, ListNode(5)))  # 1->4->5
    l2 = ListNode(1, ListNode(3, ListNode(4)))  # 1->3->4
    s = Solution()
    lists = [l1, l2]
    head = s.mergeKLists(lists)
    print(to_list(head))

if __name__ == '__main__':
    test_merge()


0 回复 有任何疑惑可以回复我~
  • 你可以通过实例化 ListNode 的定义来定义一个链表。
    l1 = ListNode(1, ListNode(4, ListNode(5)))  # 1->4->5
    回复 有任何疑惑可以回复我~ 2019-03-20 00:01:54
问题已解决,确定采纳
还有疑问,暂不采纳
Python工程师面试宝典 一线大厂资深面试官亲授
  • 参与学习       1041    人
  • 解答问题       102    个

Python工程师面试必看,资深面试官亲授,倍增面试成功率

了解课程
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号