首页 > 编程语言 >python 合并k个有序链表

python 合并k个有序链表

时间:2023-06-01 12:34:24浏览次数:43  
标签:node ListNode val python self list next 链表 有序

 

from heapq import heappush, heappop


class Solution:
    def mergeKLists(self, lists):
        q = []
        for i,head in enumerate(lists):
            if head:
                heappush(q, (head.val, i, head))

        node = dummy = ListNode(0)
        while q:
            val, i, pop_node = heappop(q)
            print(val)
            node.next = ListNode(val)
            node = node.next
            next_node = pop_node.next
            if next_node:
                heappush(q, (next_node.val, i, next_node))
        return dummy.next

  

 为啥有i???????????理由见后、

 

另外PQ也有这个问题

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import queue


class Solution:
    def mergeKLists(self, lists: List[ListNode]) -> ListNode:
        q = queue.PriorityQueue()
        for i,head in enumerate(lists):
            if head:
                q.put((head.val, i, head))
        
        node = dummy = ListNode(0)
        while not q.empty():
            val, i, pop_node = q.get()
            node.next = ListNode(val)
            node = node.next
            next_node = pop_node.next
            if next_node:
                q.put((next_node.val, i, next_node))
        return dummy.next

  

python 3 heappush Line 13: TypeError: '<' not supported between instances of 'ListNode' and 'ListNode'

出现原因:

@cbmbbz In the event that two or more of the lists have the same val, this code will error out since the queue module will compare the second element in the priority queue which is a ListNode object (and this is not a comparable type).

 

To solve for this issue, I have stored (node.val, list_idx, node) to account for this edge case.

 

from queue import PriorityQueue
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeKLists(self, lists):
        k = len(lists)
        q = PriorityQueue(maxsize=k)
        dummy = ListNode(None)
        curr = dummy
        for list_idx, node in enumerate(lists):
            if node: q.put((node.val, list_idx, node))
        while q.qsize() > 0:
            poped = q.get()
            curr.next, list_idx = poped[2], poped[1]
            curr = curr.next
            if curr.next: q.put((curr.next.val, list_idx, curr.next))
        return dummy.next

 

 

 

48

 

Show 4 replies

Reply

Share

Report

python 合并k个有序链表_Line

onedingz25

Last Edit: October 11, 2018 9:42 PM

Read More

Python3 env will get TypeError: '<' not supported between instances of 'ListNode' and 'ListNode'if there are duplicate values in the list. Works in Python env.

标签:node,ListNode,val,python,self,list,next,链表,有序
From: https://blog.51cto.com/u_11908275/6393213

相关文章

  • python代码规范 自动优化工具Black
    自动优化工具Black在众多代码格式化工具中,Black算是比较新的一个,它***的特点是可配置项比较少,个人认为这对于新手来说是件好事,因为我们不必过多考虑如何设置Black,让Black自己做决定就好。1).安装与使用与pylint类似,直接pipinstallblack即可完成该模块的安装,不过black依赖于Pyth......
  • python--PythonMagick安装过程
    一、发现问题使用:pipinstallpythonmagick安装出错:1.打开网站下载自己python版本对应的pythonmagick版本其中的cp310,cp39之类就是对应Python的版本,不知道的也可以使用pipdebug--verbose查看2.打开CMD窗口,进入到pythonmagick的安装目录3.使用import命令将jpg、png图......
  • python之struct模块处理二进制
    嵌入式开发中,有时需要对二进制流文件进行读写操作,一种方法是将二进制流文件转换为c语言数组形式。这样可以使用python的struct模块,python的struct模块可以方便的进行字节与二进制之间的相互转换。1struct模块常用的几个函数函数说明struct.pack(format,v1,v2,...)......
  • python selenium框架解决ip代理框不能自动化登录,解决pyautogui开不了多线程问题
    有时候我们使用python自动化框架的时候,打开一个网页的时候,它会出现出线这一种登录框,我们f12检查不了,用开发者工具强制检查里面没有任何属性.那这时候我们就可以用到python第三方库:pyautoguiPyAutoGUI:是一个Python库,可用于自动化GUI(图形用户界面)程序的任务。它可以让Pytho......
  • Python批量填补遥感影像的无效值NoData
      本文介绍基于Python中ArcPy模块,对大量栅格遥感影像文件批量进行无效值(NoData值)填充的方法。  在处理栅格图像文件时,我们经常会遇到图像中存在有无效值(即NoData值)的情况。如下图所示,这里有一个矢量面要素图层和该矢量图层范围对应的一景栅格图像;可以看到,由于该栅格图像存在......
  • python目录扫描工具——dirsearch使用,可以使用御剑的字典 支持慢速扫描,一般使用-s 60
    使用御剑的字典:pythondirsearch.py-uxxx.com-e*-w/media/dir_dict/ASP.txt,/media/dir_dict/ASPX.txt,/media/dir_dict/DIR.txt,/media/dir_dict/JSP.txt,/media/dir_dict/MDB.txt,/media/dir_dict/PHP.txt 非常好用!!!如下是御剑的字典文件。 进入dirsearch目录,进行扫描在这......
  • json.dumps(),json.loads(),json.dump(),json.load()方法的区别(python)
    1.json.dumps()json.dump()是将字典类型转化成字符串类型。importjsondic={'a':'1111','b':'2222','c':'3333','d':'4444'}st=json.dumps(dic)print("我是字典类型的",dic)print("我是字......
  • Flask-----轻量级的框架,快速的搭建程序(python)
     Flask是一个基于Python开发并且依赖jinja2模板和WerkzeugWSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借......
  • Python装饰器
    Python装饰器是一种语法糖,用于修改函数或类的行为,而无需修改其源代码。装饰器是一个可以接受函数或类作为参数,并返回一个新函数或类的函数。它可以用于添加功能,比如缓存、日志、计时等,或者改变函数或类的行为,比如限制访问、检查参数、实现单例等。装饰器通常定义为一个函数,该函数......
  • 合并两个有序链表
     将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。  经典算法,采用递归法就行了,别的算法也有,但有限考虑能想得到的。每次将两个头节点值较小的链表 l1 和 l2 中的头结点合并,并返回合并后的头结点,递归地进行下去,直到......