各位大牛,请看看下面这个算法, 这个是不用heap的算法。
我觉得complexity 是 O(k*n), k是list 的个数, n 是list的平均长度。
那是不是这个应该比用heap的更好点啊?
public static ListNode mergeKLists(ArrayList kLists) {
if (kLists==null)
return null;
if (kLists.size()==0)
return null;
// if there is only one list in kLists
if (kLists.size()==1)
return kLists.get(0);
int length = kLists.size();
// initialize the curList with the first item in the list
ListNode curList = kLists.get(0);
// merge the curList with the rest of the items in the list
// and save the merged list back to curList
for (int i =1; icurList = mergeTwoLists(kLists.get(i), curList);
}
// return curList as the result
return curList;
}
private static ListNode mergeTwoLists(ListNode l1, ListNode l2){
// if one list is empty, then return the other one
if(l1==null) return l2;
if(l2==null) return l1;
// create two index nodes for the two lists
ListNode indexNode1 = l1;
ListNode indexNode2 = l2;
// create a dummy head node
ListNode dummyHead = new ListNode(-1);
// create an index node for the returning merge list
ListNode indexNode = dummyHead;
// while both lists does not hit its end
while(indexNode1!=null&&indexNode2!=null){
if(indexNode1.val// add the node in list1 to the merged list
indexNode.next = indexNode1;
// move to next node in list1
indexNode1 = indexNode1.next;
}else{
// add the node in list2 to the merged list
indexNode.next = indexNode2;
// move to next node in list2
indexNode2 = indexNode2.next;
}
// update the index var in the merged list
indexNode = indexNode.next;
}
// add the rest of nodes in list1 to the returning list
if(indexNode1!=null){
indexNode.next = indexNode1;
}
// add the rest of nodes in list2 to the returning list
if(indexNode2!=null){
indexNode.next = indexNode2;
}
// return the real head
return dummyHead.next;
}