题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode mergeLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(0);
ListNode p=head, p1=l1, p2=l2;
while(p1!=null && p2!=null){
if(p1.val<p2.val){p.next = p1; p1 = p1.next;}
else {p.next = p2; p2 = p2.next;}
p = p.next;
}
if(p1!=null) p.next = p1;
if(p2!=null) p.next = p2;
return head.next;
}
public ListNode helper(List<ListNode> lists, int l, int r){
if(l>r) return null;
if(l==r) return lists.get(l);
int m = (l+r)/2;
ListNode l1 = helper(lists, l, m);
ListNode l2 = helper(lists, m+1, r);
return mergeLists(l1,l2);
}
public ListNode mergeKLists(List<ListNode> lists) {
return helper(lists, 0, lists.size()-1);//二分法merge lists
}
}
Python
<pre name="code" class="python"># Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
head=ListNode(0); dup=head;
while l1!=None and l2!=None:
if l1.val < l2.val:
dup.next = l1
l1 = l1.next
else:
dup.next = l2
l2 = l2.next
dup = dup.next
if l1==None:
dup.next = l2
elif l2==None:
dup.next = l1
return head.next
#超时
def helper1(self, lists):
l1=lists[0]
for i in range(len(lists)-1):
l2 = lists[i+1]
l1 = self.mergeTwoLists(l1, l2)
return l1
def helper2(self, lists, l, r):
if l>r: return None
elif l==r: return lists[l]
m = (l+r)/2
l1 = self.helper2(lists,l,m)
l2 = self.helper2(lists, m+1, r)
return self.mergeTwoLists(l1,l2)
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
#if lists==None: return None
#elif len(lists)<=1: return lists
return self.helper2(lists,0,len(lists)-1)