重点思想: 第一轮从k个list中拿出第一个(若每个list非空的话;有可能为空)放入minheap中,minheap一直储存k个lists中最小的那个数,对顶代表当前最小的数,需要插入result listnode。所有list每个node都要加入minheap中,所以结束条件就是minheap为空,已经便利完所有node/
Time:一共kn个node,每次插入需要O(logk),一共 O(knlogk)
Space: O(k) minheap 大小
重点:每一次将一个list中的值插入miheap中时要将指针移到下一位,方便下一次根据list的k值来加入lists[k]的下一位。
for i in range(k):
if lists[i]:#current listnode is not None
heappush(h, [lists[i].val,i])
lists[i] = lists[i].next#prepare for next around of adding into the heap
cur = cur.next
#append the next node of list k if list k has other nodes
if lists[cur_k]:
heappush(h,[lists[cur_k].val, cur_k])
lists[cur_k] = lists[cur_k].next
return res.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from heapq import *
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
h = []
k = len(lists)
for i in range(k):
if lists[i]:#current listnode is not None
heappush(h, [lists[i].val,i])
lists[i] = lists[i].next#prepare for next around of adding into the heap
res = ListNode(0)
cur = res
while h:#while heap still has remaining node left
cur_smallest_val, cur_k = heappop(h)
cur.next = ListNode(cur_smallest_val)
cur = cur.next
#append the next node of list k if list k has other nodes
if lists[cur_k]:
heappush(h,[lists[cur_k].val, cur_k])
lists[cur_k] = lists[cur_k].next
return res.next
来源:题目图片来源力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。