LeetCode 23.Merge k Sorted List 合併k個有序連結串列(後補)
阿新 • • 發佈:2019-01-28
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個,再進行合併,一直合併到一個為止。