zoukankan      html  css  js  c++  java
  • 合并有序链表

    21. 合并两个有序链表

    难度简单912收藏分享切换为英文关注反馈

    将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

    示例:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4
    
    class Solution:
        def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
            l3 = ListNode(-1)
            new = l3
            while l1 and l2:
                if l1.val < l2.val:
                    new.next = l1
                    l1 = l1.next
                else:
                    new.next = l2
                    l2 = l2.next
                new = new.next
    
            new.next = l1 if l1 is not None else l2
    
            return l3.next
    

    23. 合并K个排序链表

    合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

    示例:

    输入:
    [
      1->4->5,
      1->3->4,
      2->6
    ]
    输出: 1->1->2->3->4->4->5->6
    
    #两两合并,分治
    class Solution:
        def mergeKLists(self, lists: List[ListNode]) -> ListNode:
            #两两合并,分治
            if not lists:
                return None
            
            start,end = 0,len(lists)-1
            return self.merge(lists,start,end)
                
        def merge(self,lists,start,end):
            if start == end:
                return lists[start]
            mid = start+(end-start)//2
            l1 = self.merge(lists,start,mid)
            l2 = self.merge(lists,mid+1,end)
            return self.merge2list(l1,l2)
        
        def merge2list(self,l1,l2):
            l3 = ListNode(-1)
            new = l3
            while l1 and l2:
                if l1.val < l2.val:
                    new.next = l1
                    l1 = l1.next
                else:
                    new.next = l2
                    l2 = l2.next
                new = new.next
    
            new.next = l1 if l1 is not None else l2
    
            return l3.next
    
  • 相关阅读:
    hbase存储优化
    cloudera manager下phoenix的安装
    Cloudera manager的服务安装以及spark升级到2.2
    redis学习总结
    kylin基础概念和基础性能优化
    mycat使用注意事项
    kylin2.0环境搭建
    ETL实践--kettle转到hive
    集成 SOLR 到 TOMCAT 中(傻瓜教程)
    局域网ip扫描
  • 原文地址:https://www.cnblogs.com/gongyanzh/p/12588912.html
Copyright © 2011-2022 走看看