R4-分治篇
目录
最小堆方法
分治法
ps:
如果只是数组就很好处理了
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
stack=[]
for row in lists:
for r in row:
stack.append(r)
stack.sort()
return stack
最小堆方法
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#堆可以比较节点大小
ListNode.__lt__=lambda a,b : a.val<b.val
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
#cur是指针,随时合并下一个节点。
#dummy是哨兵,dummy.next返回最终的链表
#h是最小堆
cur = dummy =ListNode()
#所有头节点入堆
h=[head for head in lists if head]
#堆化(前提是堆能比较节点大小)
heapify(h)
while h:
node=heappop(h)
if node.next:
heappush(h,node.next)
cur.next=node
cur=cur.next
return dummy.next
分治法
灵神题解
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
#堆可以比较节点大小
ListNode.__lt__=lambda a,b : a.val<b.val
class Solution:
#合并两个有序链表
def mergeTwoLists(self,list1,list2):
cur = dummy =ListNode()
while list1 and list2:
if list1.val<list2.val:
cur.next=list1
list1=list1.next
else:
cur.next=list2
list2=list2.next
cur=cur.next
#拼接剩余链表
cur.next=list1 if list1 else list2
return dummy.next
#本题合并所有升序链表
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
m=len(lists)
if m==0:
return None
if m==1:
return lists[0]
left=self.mergeKLists(lists[:m//2])
right=self.mergeKLists(lists[m//2:])
return self.mergeTwoLists(left,right)
牛啊
ps:
今天get到堆的出堆等基本操作方法