Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
題目描述
講k個有序鏈表合併爲一個鏈表,並且保持有序狀態。
思路1
將所有的鏈表的頭結點放到最小堆裏面,每提取一個結點,就將該結點的下一個結點放在堆裏。
public class MergeKSortedList {
public ListNode mergeKLists(ArrayList<ListNode> lists) {
if ( lists.size()==0 || lists==null ) {
return null;
} else {
PriorityQueue<ListNode> que = new PriorityQueue<>( lists.size(),new Comparator<ListNode>() {
public int compare(ListNode o1, ListNode o2) {
return o1.val-o2.val;
}
});
ListIterator<ListNode> it = lists.listIterator();
while ( it.hasNext() ) {
ListNode temp = it.next();
if ( null!=temp ) {
que.add(temp);
}
}
ListNode root = que.poll();
// 有比較多的坑點
if ( root.next!=null ) {
que.add(root.next);
}
ListNode head = root;
while ( !que.isEmpty() ) {
ListNode t = que.poll();
if( t.next!=null ) {
que.add(t.next);
}
head.next = t;
head = head.next;
}
return root;
}
}
}
思路2
可以借鑑歸併排序的思路,先將n個鏈表中一一合併爲n/2個,再進行合併,一直合併到一個爲止。