中等 合并k个排序链表
24%
通过
合并k个排序链表,并且返回合并后的排序链表。尝试分析和描述其复杂度。
Yes
样例
给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null
package test.mergeSort;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import test.mergeSort.ListNode;
/**
* public class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
*
*
* @author Howard_Zhou
*
*/
public class Solution {
/**
* @param lists: a list of ListNode
* @return: The head of one sorted list.
*/
private Comparator<ListNode> ListNodeComparator = new Comparator<ListNode>() {
public int compare(ListNode left, ListNode right) {
if (left == null) {
return 1;
} else if (right == null) {
return -1;
}
return left.val - right.val;
}
};
public ListNode mergeKLists(List<ListNode> lists) {
if (lists == null || lists.size() == 0) {
return null;
}
Queue<ListNode> heap = new PriorityQueue<ListNode>(lists.size(), ListNodeComparator);
for (int i = 0; i < lists.size(); i++) {
if (lists.get(i) != null) {
//将每个小list的头添加到heap中,这些头添加进去后被排序了(通过heap的ListNodeComparator)
heap.add(lists.get(i));
}
}
//dummy没用,dummy.next指向新链表的头
ListNode dummy = new ListNode(0);
//tail是新指针
ListNode tail = dummy;
while (!heap.isEmpty()) {
//poll会把heap中的最小元素(head)取出并删除
ListNode head = heap.poll();
//构建新链表
tail.next = head;
tail = head;
if (head.next != null) {
//head所在的小list中如果有head.next就把它添加进heap,这样实现了排序
heap.add(head.next);
}
}
return dummy.next;
}
public static void main(String[] args) {
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(4);
ListNode node3 = new ListNode(-1);
node1.next = node2;
List<ListNode> lists = new LinkedList<ListNode>();
lists.add(node1);
lists.add(node3);
Solution solution = new Solution();
ListNode mergeKLists = solution.mergeKLists(lists);
System.out.println(mergeKLists);
}
}