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=nodecur=cur.nextreturn 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=list1list1=list1.nextelse:cur.next=list2list2=list2.nextcur=cur.next#拼接剩余链表cur.next=list1 if list1 else list2return dummy.next#本题合并所有升序链表def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:m=len(lists)if m==0:return Noneif m==1:return lists[0]left=self.mergeKLists(lists[:m//2])right=self.mergeKLists(lists[m//2:])return self.mergeTwoLists(left,right)
牛啊
ps:
今天get到堆的出堆等基本操作方法