Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
思路:选择两个list中第一个元素最小的为基础,然后将另外一个list的元素逐渐和第一个list中的元素相比,并将其插入到第一个list中,最终返回第一个list的头即可。
时间复杂度:O(M+N)
空间复杂度:O(M+N)
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val>l2.val)
return mergeTwoLists(l2,l1);
ListNode head=l1;
ListNode temp;
while(l2!=null){
while(l1.next!=null&&l2.val>l1.next.val)
l1=l1.next;
if(l1.next==null){
l1.next=l2;
return head;
}else{
temp=l2;
l2=l2.next;
temp.next=l1.next;
l1.next=temp;
l1=l1.next;
}
}
return head;
}
递归算法:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val<l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
23. Merge k Sorted Lists
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路: 两两合并,每次将两个listnode合并成一个. 利用到上述实现2个有序list合并的代码.
时间复杂度:O(N*logK) N为所有lists所包含的节点个数
public ListNode mergeKLists(ListNode[] lists) {
int len=lists.length;
if(lists==null||len==0)
return null;
return mergeKList(lists,0,len-1);
}
public ListNode mergeKList(ListNode[] lists,int left, int right) {
int len=right-left;
if(len==0)
return lists[left];
else if(len==1){
return mergeTwoLists(lists[left],lists[right]);
}else{
return mergeTwoLists(mergeKList(lists,left,left+len/2),mergeKList(lists,len/2+left+1,right));
}
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val<l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}