三个月算法进阶--day87
目录
子集
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
def backtrack(first = 0, curr = []):
if len(curr) == k:
output.append(curr[:])
for i in range(first, n):
curr.append(nums[i])
backtrack(i + 1, curr)
curr.pop()
output = []
n = len(nums)
for k in range(n + 1):
backtrack()
return output
二叉树最大路径和
class Solution:
def __init__(self):
self.ans = float("-inf")
def maxPathSum(self, root: TreeNode) -> int:
def dfs(root):
if not root:
return 0
left = max(dfs(root.left), 0)
right = max(dfs(root.right), 0)
self.ans = max(self.ans, left + root.val + right)
return root.val + max(left, right)
dfs(root)
return self.ans
环形链表
class Solution:
def hasCycle(self, head: ListNode) -> bool:
slow = head
fast = head
while fast:
fast = fast.next
if fast:
fast = fast.next
if fast == slow:
return True
slow = slow.next
return False
快速排序
def quickSort(alist):
quickSortHelper(alist, 0, len(alist)-1)
def quickSortHelper(alist, first, last):
if first < last:
splitpoint = partition(alist, first, last)
quickSortHelper(alist, first, splitpoint-1)
quickSortHelper(alist, splitpoint+1, last)
def partition(alist, first, last):
pivotvalue = alist[first]
leftmark = first + 1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark += 1
while leftmark <= rightmark and alist[rightmark] >= pivotvalue:
rightmark -= 1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
链表快排
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
target = head.val
ptr = head
small, equal, large = None, None, None
while ptr:
temp = ptr.next
if ptr.val < target:
ptr.next = small
small = ptr
elif ptr.val > target:
ptr.next = large
large = ptr
else:
ptr.next = equal
equal = ptr
ptr = temp
left = self.sortList(small)
right = self.sortList(large)
ret = ListNode()
cur = ret
for node in (left, equal, right):
if node:
cur.next = node
node = node.next
cur = cur.next
while node:
node = node.next
cur = cur.next
return ret.next
LRU
class LRUCache(collections.OrderedDict):
def __init__(self, capacity: int):
super().__init__()
self.capacity = capacity
def get(self, key: int) -> int:
if key not in self:
return -1
self.move_to_end(key)
return self[key]
def put(self, key: int, value: int) -> None:
if key in self:
self.move_to_end(key)
self[key] = value
if len(self) > self.capacity:
self.popitem(last=False)