Description
- 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