• leetcode-hard-ListNode-23. Merge k Sorted Lists


    mycode   91.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
            """
            
            res = []
            for li in lists:
                while li:
                    res.append(li.val)
                    li = li.next
            if not res :
                return None
            res = sorted(res)
            print(res)
            length = len(res)
            i = 0
            dummy = head = ListNode(-1)
            while i < length: 
                head.next = ListNode(res[i])
                head = head.next   
                i += 1
            return dummy.next

    但是下面的这个代码最后的链表就只有1一个val

    # 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
            """
            
            res = []
            for li in lists:
                while li:
                    res.append(li.val)
                    li = li.next
            if not res :
                return None
            res = sorted(res)
            print(res)
            length = len(res)
            i = 0
            dummy = head = ListNode(res[0])
            head = head.next
            while i < length - 1:
                i += 1
                #print(i)
                head = ListNode(res[i])
                #print(head.val)
                head = head.next
            return dummy
    Input:[[1,4,5],[1,3,4],[2,6]]
    Output:[1]
    Expected:[1,1,2,3,4,4,5,6]
    Stdout:[1, 1, 2, 3, 4, 4, 5, 6]
     
     
    参考
    class Solution:
        def mergeKLists(self, lists):
            nums, dum = [], ListNode(0)
            p = dum
            for l in lists:
                while l:
                    nums.append(l)
                    l = l.next
            for i in sorted(nums, key = lambda l: l.val):
                p.next = i
                p = p.next
            return dum.next
            
  • 相关阅读:
    shell脚本编程-重定向
    web安全-剖析_基础构架剖析
    shell脚本编程-函数
    shell脚本编程-循环
    web安全-入侵基础
    shell脚本编程-检查和测试
    shell脚本编程-特殊字符
    shell脚本编程-计算方式
    python例子-抓取网站IP列表
    linux问题-APR not Found
  • 原文地址:https://www.cnblogs.com/rosyYY/p/11050007.html
Copyright © 2020-2023  润新知