Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Tips:
建个堆,哪个小往里压。
复杂度: O(nlog(k)), where k is the size of the list array.
Code:
public class Solution {
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0) return null;
PriorityQueue<ListNode> pq = new PriorityQueue<>(new Comparator<ListNode>() {
public int compare(ListNode a, ListNode b) {
return a.val - b.val;
}
});
for (ListNode node : lists) {
if (node != null) pq.offer(node);
}
ListNode dummy = new ListNode(0);
ListNode head = dummy;
while (!pq.isEmpty()) {
ListNode curt = pq.poll();
head.next = curt;
head = head.next;
if (curt.next != null) pq.offer(curt.next);
}
return dummy.next;
}
}