Python 解LeetCode:23. Merge k Sorted Lists
阿新 • • 發佈:2017-12-22
取出 指針 div mark body merge spa ext 頭指針
題目描述:把k個排序的鏈表組成的列表合並成一個排序的鏈表
- 思路:
- 使用堆排序,遍歷列表,把每個列表中鏈表的頭指針的值和頭指針本身作為一個元素放在堆中;
- 第一步中遍歷完列表後,此時堆中最多會有n個元素,n是列表的長度;
- 當堆不為空,取出堆中的最小值,然後把該值的指針指向下一個元素,並入堆;
- 第3步可以確保堆永遠是o(n)大小的;
- 堆為空返回頭結點就可以了
# 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
"""
import heapq
min_heap = []
ret = head = ListNode(0)
for k, link in enumerate(lists):
if link:
heapq.heappush(min_heap, [link.val, link])
while min_heap:
cur = heapq.heappop(min_heap)
ret.next = cur[-1]
ret = ret.next
if ret.next:
heapq.heappush(min_heap, [ret.next.val, ret.next])
return head.next
Python 解LeetCode:23. Merge k Sorted Lists