合并K个有序数组
题目
合并K个有序数组
My Thought
一、将ListNode放入PriorityQueue中
1.1、设置PriorityQueue的比较器规则
1.2、将ListNode[] 放入priorityQueue
二、再将数据依次弹出放到ListNode中
代码示例
JAVA-8
public ListNode mergeKLists(ListNode[] lists) {
PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(new ListNodeComparator());
for (ListNode list : lists) {
if (list != null) {
priorityQueue.add(list);
}
}
if (priorityQueue.isEmpty()) {
return null;
}
ListNode head = null;
ListNode pre = null;
while (!priorityQueue.isEmpty()) {
ListNode current = priorityQueue.poll();
if(head == null){
head = current;
pre = head;
}else{
pre.next = current;
pre = current;
}
if (current.next != null){
priorityQueue.add(current.next);
}
}
return head;
}
public static class ListNodeComparator implements Comparator<ListNode> {
@Override
public int compare(ListNode o1, ListNode o2) {
return o1.val - o2.val;
}
}