# 【LeetCode】23. Merge k Sorted Lists 合并K个升序链表

900 篇文章 155 订阅
1033 篇文章 56 订阅
• 作者： 负雪明烛
• id： fuxuemingzhu
• 个人博客：http://fuxuemingzhu.cn/
• 个人公众号：负雪明烛
• 本文关键词：合并，链表，单链表，题解，leetcode, 力扣，Python, C++, Java

## 题目描述：

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


## 解题方法

### 方法一：每次遍历最小值（TLE）

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

class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
while True:
curIndex = -1
for i, llist in enumerate(lists):
if llist and llist.val < curHead.val:
curIndex = i
break


### 方法二：小根堆保存值和索引

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

class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
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)


### 方法三：小根堆保存值和节点

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

class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
heap = []
heapq.heapify(heap)
[heapq.heappush(heap, (l.val, l)) for i, l in enumerate(lists) if l]
while heap:


## 日期

2018 年 10 月 16 日 —— 下雨天还是挺舒服的

• 0
点赞
• 0
收藏
• 打赏
• 4
评论
12-08 250
09-05 92
03-07 1634
04-21 2171
03-20 810
09-12 247
06-20 871

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

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