23. Merge k Sorted Lists
Hard
Last updated
Was this helpful?
Hard
Last updated
Was this helpful?
Key idea: using PriorityQueue to implement minimal heap
核心:用有限队列实现最小堆
add the head of each list to heap
poll out top of heap adding to new linked list
add this element's next to heap
until heap is empty
PriorityQueue doesn't accept null, so before adding element, judge whether it is null
优先序列这种数据结构不接收空元素,所以在加入元素前先判断是否为空
PriorityQueue only accepts comparable elements, self-define data structure mustn't be comparable, so override comparator function of PriorityQueue is necessary
优先序列只接受能比较大小的元素,自定义的数据结构是不可比较的,因此必须重写comparator,然后用comparator去初始化优先序列
Why using PriorityQueue to implement heap?
Because any element added to PriorityQueue, it will be sorted in automatically in acceding order. Therefore, adding and deleting an element for PriorityQueue is , find the smallest element is . So solving this problem takes