Python中优先队列与链表
富比较
python中排序的调用是类里面的特殊方法__lt__和__gt__实现的。
称为富比较方法,详细查看博文富比较
定义以下类
class Skill(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
def __lt__(self, other):
return self.priority < other.priority
def get(self):
return self.description
a = Skill(5, 'head')
b = Skill(6, 'head')
a>b
False
Leetcode23.合并k个升序链表
默认定义的ListNode增加__lt__方法可以实现使用queue.PriorityQueue优先队列进行排序。
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def __lt__(self, other):
return self.val < other.val
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists:
return None
p = ListNode(-1)
head = p
pq = PriorityQueue()
for cur in lists:
if cur != None:
pq.put((cur.val,cur))
while not pq.empty():
node = pq.get()[1]
# print(node)
p.next = node
if node.next != None:
pq.put((node.next.val,node.next))
p = p.next
return head.next
说明:代码中使用了元组,元组在优先队列里面排序会从第一个元素开始比较,第一个元素相同再比较第二个元素,但是由于第二个元素ListNode类,不能进行比较。所以才修改默认ListNode类增加__lt__方法。
在本地调试可以通过,但是可能是因为Leetcode不支持修改默认定义的单链表,所以线上未通过。在本地调试中,元组都可以不需要,直接放入ListNode就可以比较。再尝试以下方法,自定义一个新的比较类。即上文的Skill
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
from queue import PriorityQueue
class Skill(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
def __le__(self, other):
return self.priority <= other.priority
def __lt__(self, other):
return self.priority < other.priority
def get(self):
return self.description
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
if not lists:
return None
p = ListNode(-1)
head = p
pq = PriorityQueue()
for cur in lists:
if cur != None:
pq.put(Skill(cur.val,cur))
# print(pq.empty())
while not pq.empty():
node = pq.get().get()
# print(node)
p.next = node
if node.next != None:
pq.put(Skill(node.next.val,node.next))
p = p.next
return head.next
这样在线上是可以通过的,就是比较耗时。