• 合并多个有序链表


    Python解决方案1:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
            all_list = []
            for i in lists:
                all_list += self.tolist(i)
            all_list.sort()
            if not all_list:
                return None
            head = ListNode(all_list[0])
            out = head
            for i in all_list[1:]:
                head.next = ListNode(i)
                head = head.next
            return out
            
        def tolist(self,head):
            out = []
            while head:
                out.append(head.val)
                head = head.next
            return out

    Python解决方案2:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
        
            length = len(lists)
            if length == 0:
                return None
            else:
                while len(lists) > 1:
                    lists.append(self.mergeTwoLists(lists.pop(0),lists.pop(0)))
                return lists[0]
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            prev = ListNode(0)
            head = prev
            while l1 and l2:
                if l1.val <= l2.val:
                    prev.next = l1
                    l1 = l1.next
                else:
                    prev.next = l2
                    l2 = l2.next
                prev = prev.next
            if l1:
                prev.next = l1
            if l2:
                prev.next = l2  
            return head.next
  • 相关阅读:
    Lock、Synchronized锁解析
    js多个计时器互不影响触发
    php Excel文件导入 Spreadsheet_Excel_Reader
    Tcp/ip简介
    对称加密和非对称加密
    AFNetworking 3.0迁移指南
    从 Objective-C 里的 Alloc 和 AllocWithZone 谈起
    iOS 沙盒
    SDWebImage解析
    dSYM文件
  • 原文地址:https://www.cnblogs.com/wenqinchao/p/10620450.html
Copyright © 2020-2023  润新知