【leetcode】(python) 23. Merge k Sorted Lists

这篇博客讨论了如何使用Python解决LeetCode上的23题——合并k个排序链表。通过堆排序思想,将链表头节点放入小根堆中,每次取出最小值并更新堆,以构建一个有序链表。此外,还提供了另一种解决方案,即先将所有链表的元素放入列表,再对列表排序。这两种方法的时间和内存消耗也进行了比较。
摘要由CSDN通过智能技术生成

Description

  1. Merge k Sorted Lists hard
    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

题目大意

将k个升序链表合成一个升序链表

解体思路

利用堆排序思想,首先将k个链表的头节点放入堆中进行小根堆排序,这样可以得到最小值及其下标号,然后继续将最小数链表的下一个数放入堆中进行小根堆排序,以此类推。

code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        head = ListNode(-1)
        move = head
        heap = []
        heapq.heapify(heap)
        [heapq.heappush(heap, (l.val, i)) for i, l in enumerate(lists) if l]
        while heap:
            curVal, curIndex = heapq.heappop(heap)
            curHead = lists[curIndex]
            curNext = curHead.next
            move.next = curHead
            curHead.next = None
            move = curHead
            curHead = curNext
            if curHead:
                lists[curIndex] = curHead
                heapq.heappush(heap, (curHead.val, curIndex))
        return head.next

Runtime:68ms, Memory:16.4 MB

参考较优解

解题思路

依次遍历每个链表并将其值放入一列表中,最后将列表排序即可。

code

buf = []
        for i in range(len(lists)):
            while(lists[i] is not None):
                # print(lists[i].val)
                buf.append(lists[i].val)
                lists[i] = lists[i].next
        buf.sort()
        return buf

Runtime:64ms, Memory:15.8 MB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值