新博文总结了三种算法,新博文地址:[leetcode]Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
K路归并,不知道大家对2路归并还有木有印象,如果木有的话,请戳这里。
其实K路归并,就是进行k - 1 次二路归并,完全一样。
代码如下:
public ListNode mergeKLists(ArrayList<ListNode> lists){
ListNode result = new ListNode(0);
if(lists == null || lists.size() == 0 ){
return null;
}
if(lists.size() == 1){
return lists.get(0);
}
result = merge2List(lists.get(0),lists.get(1));
for(int i = 2; i < lists.size();i++){
result = merge2List(result,lists.get(i));
}
return result;
}
private ListNode merge2List(ListNode l1,ListNode l2){
ListNode l1Tail = l1;
ListNode l2Tail = l2;
ListNode list = new ListNode(0);
ListNode tail = list;
while(l1Tail != null || l2Tail != null){
if(l1Tail == null){
tail.next = l2Tail;
break;
}
if(l2Tail == null){
tail.next = l1Tail;
break;
}
if(l1Tail.val < l2Tail.val){
tail.next = l1Tail;
l1Tail = l1Tail.next != null ? l1Tail.next : null;;
}else{
tail.next = l2Tail;
l2Tail = l2Tail.next != null ? l2Tail.next : null;
}
tail = tail.next;
}
return list.next;
}