[leetcode]Merge k Sorted Lists @ Python [基础知识: heap]
原题地址:https://oj.leetcode.com/problems/merge-k-sorted-lists/
题意:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
解题思路:
归并k个已经排好序的链表, 使用堆这一数据结构. 堆,也叫做:priority queue
首先将每条链表的头节点进入堆中.
然后将最小的弹出,并将最小的节点这条链表的下一个节点入堆,依次类推,最终形成的链表就是归并好的链表。
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a list of ListNode # @return a ListNode def mergeKLists(self, lists): heap = [] for head in lists: if head: heap.append((head.val, head)) heapq.heapify(heap) dummy = ListNode(0) curr = dummy while heap: (val, node) = heapq.heappop(heap) curr.next = ListNode(val) curr = curr.next if node.next: heapq.heappush(heap, (node.next.val, node.next)) return dummy.next #heapq.heappush(heap, item): Push the value item onto the heap, maintaining the heap invariant. #heapq.heappop(heap): Pop and return the smallest item from the heap, maintaining the heap invariant. #https://docs.python.org/2/library/heapq.html