题目描述
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
方法思路
Approach1:
class Solution {
//Runtime: 13 ms, faster than 54.98%
//Memory Usage: 38.8 MB, less than 62.33%
public ListNode mergeKLists(ListNode[] lists) {
if(lists.length == 0) return null;
List<ListNode> listArray = new ArrayList<>();
ListNode node = null;
for(ListNode l : lists)
listArray.add(l);
while(listArray.size() > 1){
node = mergeTwoSortedLists(listArray.get(0), listArray.get(1));
listArray.remove(1);
listArray.remove(0);
listArray.add(node);
}
return listArray.get(0);
}
public ListNode mergeTwoSortedLists(ListNode l1, ListNode l2){
if(l1 == null) return l2;
else if(l2 == null) return l1;
ListNode dummy = new ListNode(0), help = dummy;
while(l1 != null && l2 != null){
if(l1.val <= l2.val){
help.next = l1;
l1 = l1.next;
}else{
help.next = l2;
l2 = l2.next;
}
help = help.next;
}
if(l1 != null)
help.next = l1;
else if(l2 != null)
help.next = l2;
return dummy.next;
}
}
Approach2: a java solution based on Priority Queue
If someone understand how priority queue works, then it would be trivial to walk through the codes.
My question: is that possible to solve this question under the same time complexity without implementing the priority queue?
class Solution{
public class Solution {
public ListNode mergeKLists(List<ListNode> lists) {
if (lists==null||lists.size()==0) return null;
PriorityQueue<ListNode> queue =
new PriorityQueue<ListNode>(lists.size(),new Comparator<ListNode>(){
@Override
public int compare(ListNode o1,ListNode o2){
if (o1.val<o2.val)
return -1;
else if (o1.val==o2.val)
return 0;
else
return 1;
}
});
ListNode dummy = new ListNode(0);
ListNode tail=dummy;
for (ListNode node:lists)
if (node!=null)
queue.add(node);
while (!queue.isEmpty()){
tail.next=queue.poll();
tail=tail.next;
if (tail.next!=null)
queue.add(tail.next);
}
return dummy.next;
}
}
}
Approach3: simple java Solution use recursion
public static ListNode mergeKLists(ListNode[] lists){
return partion(lists,0,lists.length-1);
}
public static ListNode partion(ListNode[] lists,int s,int e){
if(s==e) return lists[s];
if(s<e){
int q=(s+e)/2;
ListNode l1=partion(lists,s,q);
ListNode l2=partion(lists,q+1,e);
return merge(l1,l2);
}else
return null;
}
//This function is from Merge Two Sorted Lists.
public static ListNode merge(ListNode l1,ListNode l2){
if(l1==null) return l2;
if(l2==null) return l1;
if(l1.val<l2.val){
l1.next=merge(l1.next,l2);
return l1;
}else{
l2.next=merge(l1,l2.next);
return l2;
}
}