21.23. Merge Two Sorted Lists /

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;  
            }  
          
        }  



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值