25. K 个一组翻转链表
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
nums = []
for l in lists:
while l:
nums.append(l.val)
l = l.next
nums.sort()
cur = head = ListNode(0)
for i in nums:
cur.next = ListNode(val=i)
cur= cur.next
return head.next
5. 最长回文子串
33. 搜索旋转排序数组
200. 岛屿数量
92. 反转链表 II
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
head=ListNode(0)
current=head
while list1 and list2:
if list1.val>=list2.val:
current.next=list2
list2=list2.next
else:
current.next=list1
list1=list1.next
current=current.next
current.next= list1 if list1 else list2
return head.next
23. 合并K个排序链表
from queue import PriorityQueue
class Solution:
def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
nums = []
for l in lists:
while l:
nums.append(l.val)
l = l.next
nums.sort()
cur = head = ListNode(0)
for i in nums:
cur.next = ListNode(val=i)
cur= cur.next
return head.next
143. 重排链表
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head or not head.next: return head
fast = head
pre_mid = head
while fast.next and fast.next.next:
pre_mid = pre_mid.next
fast = fast.next.next
pre = None
cur = pre_mid.next
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
pre_mid.next = pre
p1 = head
p2 = pre_mid.next
while p1 != pre_mid:
pre_mid.next = p2.next
p2.next = p1.next
p1.next = p2
p1 = p2.next
p2 = pre_mid.next
124. 二叉树中的最大路径和
class Solution:
def maxPathSum(self, root: Optional[TreeNode]) -> int:
self.ans = float("-inf")
def maxGain(r):
if not r:
return 0
left = max(maxGain(r.left), 0)
right = max(maxGain(r.right), 0)
self.ans = max(self.ans, r.val+left+right)
return r.val+max(left, right)
maxGain(root)
return self.ans
补充题23. 检测循环依赖
468. 验证IP地址