树
1、按之字形顺序打印二叉树(done)
剑指 Offer 32 - III. 从上到下打印二叉树 III
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
res = []
if not root:
return []
from collections import deque
que = deque([root])
while que:
result = deque()
for _ in range(len(que)):
cur = que.popleft()
if len(res) % 2: result.appendleft(cur.val) # 偶数层 -> 队列头部
else: result.append(cur.val) # 奇数层 -> 队列尾部
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
res.append(list(result))
return res
2、从上到下打印二叉树(done)
class Solution:
def levelOrder(self, root: TreeNode) -> List[int]:
ans = []
if not root:
return ans
from collections import deque
que = deque([root])
while que:
for _ in range(len(que)):
cur = que.popleft()
ans.append(cur.val)
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
return ans
3、 从上到下打印二叉树 II(done)
剑指 Offer 32 - II. 从上到下打印二叉树 II
class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
ans = []
if not root:
return ans
from collections import deque
que = deque([root])
while que:
result = []
for _ in range(len(que)):
cur = que.popleft()
result.append(cur.val)
if cur.left:
que.append(cur.left)
if cur.right:
que.append(cur.right)
ans.append(result)
return ans
4、树的子结构(again)
class Solution:
def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
def recur(A, B):
if not B: return True
if not A or A.val != B.val: return False
return recur(A.left, B.left) and recur(A.right, B.right)
return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))
5、路径总和(again)
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
def isornot(root, targetsum) -> bool:
if (not root.left) and (not root.right) and targetsum == 0:
return True # 遇到叶子节点,并且计数为0
if (not root.left) and (not root.right):
return False # 遇到叶子节点,计数不为0
if root.left:
targetsum -= root.left.val # 左节点
if isornot(root.left, targetsum): return True # 递归,处理左节点
targetsum += root.left.val # 回溯
if root.right:
targetsum -= root.right.val # 右节点
if isornot(root.right, targetsum): return True # 递归,处理右节点
targetsum += root.right.val # 回溯
return False
if not root:
return False # 别忘记处理空treenode
else:
return isornot(root, targetSum - root.val)
6、路径总和ii(again)
class Solution:
def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
ret = list()
path = list()
def dfs(root: TreeNode, targetSum: int):
if not root:
return
path.append(root.val)
targetSum -= root.val
if not root.left and not root.right and targetSum == 0:
ret.append(path[:])
dfs(root.left, targetSum)
dfs(root.right, targetSum)
path.pop()
dfs(root, targetSum)
return ret
7、路径总和iii(again)
class Solution:
def pathSum(self, root: TreeNode, targetSum: int) -> int:
def rootSum(root, targetSum):
if root is None:
return 0
ret = 0
if root.val == targetSum:
ret += 1
ret += rootSum(root.left, targetSum - root.val)
ret += rootSum(root.right, targetSum - root.val)
return ret
if root is None:
return 0
ret = rootSum(root, targetSum)
ret += self.pathSum(root.left, targetSum)
ret += self.pathSum(root.right, targetSum)
return ret
8、二叉树中的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if not root or root == p or root == q:
return root
left = self.lowestCommonAncestor(root.left,p,q)
right = self.lowestCommonAncestor(root.right,p,q)
if left and right:
return root
return left if left else right
9、二叉搜索树的最近公共祖先
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root.val > p.val and root.val > q.val: #在左边
return self.lowestCommonAncestor(root.left,p,q)
if root.val < p.val and root.val < q.val: #右边
return self.lowestCommonAncestor(root.right,p,q)
return root
10、二叉搜索树的后序遍历序列
栈
1、栈的压入、弹出序列(……)
class Solution:
def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
stack, i = [], 0
for num in pushed:
stack.append(num) # num 入栈
while stack and stack[-1] == popped[i]: # 循环判断与出栈
stack.pop()
i += 1
return not stack
2、滑动窗口最大值(单调队列……不会)
class MyQueue: #单调队列(从大到小
def __init__(self):
self.queue = [] #使用list来实现单调队列
#每次弹出的时候,比较当前要弹出的数值是否等于队列出口元素的数值,如果相等则弹出。
#同时pop之前判断队列当前是否为空。
def pop(self, value):
if self.queue and value == self.queue[0]:
self.queue.pop(0)#list.pop()时间复杂度为O(n),这里可以使用collections.deque()
#如果push的数值大于入口元素的数值,那么就将队列后端的数值弹出,直到push的数值小于等于队列入口元素的数值为止。
#这样就保持了队列里的数值是单调从大到小的了。
def push(self, value):
while self.queue and value > self.queue[-1]:
self.queue.pop()
self.queue.append(value)
#查询当前队列里的最大值 直接返回队列前端也就是front就可以了。
def front(self):
return self.queue[0]
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
que = MyQueue()
result = []
for i in range(k): #先将前k的元素放进队列
que.push(nums[i])
result.append(que.front()) #result 记录前k的元素的最大值
for i in range(k, len(nums)):
que.pop(nums[i - k]) #滑动窗口移除最前面元素
que.push(nums[i]) #滑动窗口前加入最后面的元素
result.append(que.front()) #记录对应的最大值
return result
搜索算法
1、 二维数组中的查找(done)
class Solution:
def Find(self , target: int, array: List[List[int]]) -> bool:
# write code here
n = len(array)
m = len(array[0])
if n == 0 or m == 0:
return False
left,right = n-1,0
while left >= 0 and right < m:
total = array[left][right]
if total == target:
return True
elif total > target:
left -= 1
else:
right += 1
return False
2、旋转数组的最小数字(done)
class Solution:
def minArray(self, numbers: List[int]) -> int:
low, high = 0, len(numbers) - 1
while low < high:
pivot = low + (high - low) // 2
if numbers[pivot] < numbers[high]: #右边有序且递增,故最小值在左边
high = pivot
elif numbers[pivot] > numbers[high]:
low = pivot + 1
else: #nums[m]=nums[j] 时: 无法判断 m 在哪个排序数组中,即无法判断旋转点 x 在 [i,m] 还是[m+1,j] 区间中。解决方案: 执行j=j−1 缩小判断范围
high -= 1
return numbers[low]
3、字符串的排列(……again)
class Solution:
def Permutation(self , str: str) -> List[str]:
# write code here
if not str:
return []
ans = []
used = [0] * len(str)
def backtraver(nums,used,path):
if len(path) == len(nums):
ans.append(''.join(path[:]))
return
for i in range(len(nums)):
if not used[i]:
if i > 0 and nums[i] == nums[i-1] and not used[i-1]:
continue
used[i] = 1
path.append(nums[i])
backtraver(nums, used, path)
path.pop()
used[i] = 0
backtraver(sorted(list(str)), used,[])
return ans
动规
1、最长不含重复字符的子字符串(done)
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if not s:
return 0
stack = [s[0]]
ans = 1
for i in s:
while i in stack :
stack.pop(0)
stack.append(i)
ans = max(ans,len(stack))
return ans
2、把数字翻译成字符串(……)
3、连续子数组的最大和(done)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = [0] * len(nums)
ans = nums[0]
for i in range(len(nums)):
dp[i] = max(dp[i-1] + nums[i],nums[i])
ans = max(dp[i],ans)
return ans
4、丑数(……)
class Solution:
def nthUglyNumber(self, n: int) -> int:
dp, a, b, c = [1] * n, 0, 0, 0
for i in range(1, n):
n2, n3, n5 = dp[a] * 2, dp[b] * 3, dp[c] * 5
dp[i] = min(n2, n3, n5)
if dp[i] == n2: a += 1
if dp[i] == n3: b += 1
if dp[i] == n5: c += 1
return dp[-1]
5、剪绳子 I
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0] * (n + 1)
dp[2] = 1
# 假设对正整数 i 拆分出的第一个正整数是 j(1 <= j < i),则有以下两种方案:
# 1) 将 i 拆分成 j 和 i−j 的和,且 i−j 不再拆分成多个正整数,此时的乘积是 j * (i-j)
# 2) 将 i 拆分成 j 和 i−j 的和,且 i−j 继续拆分成多个正整数,此时的乘积是 j * dp[i-j]
for i in range(3, n + 1):
for j in range(1,i):
dp[i] = max(dp[i], j * (i - j), j * dp[i - j])
return dp[n]
6、剪绳子 II
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 2 :
return n-1
dp = [0] *(n+1)
dp[2] = 1
for j in range(3,n+1):
for i in range(1,j):
dp[j] = max(dp[j],i*(j-i),i*dp[j-i])
return dp[n]%1000000007
class Solution:
def cuttingRope(self, n: int) -> int:
if n <= 3: return n - 1
a, b, p = n // 3, n % 3, 1000000007
if b == 0: return 3 ** a % p
if b == 1: return 3 ** (a - 1) * 4 % p
return 3 ** a * 2 % p
回溯
1、矩阵中的路径
class Solution:
def exist(self, board: List[List[str]], word: str) -> bool:
#当前元素在矩阵 board 中的行列索引 i 和 j ,当前目标字符在 word 中的索引 k
def dfs(i, j, k):
if not 0 <= i < len(board) or not 0 <= j < len(board[0]) or board[i][j] != word[k]: return False
if k == len(word) - 1: return True
# 将 board[i][j] 修改为 空字符 '' ,代表此元素已访问过,防止之后搜索时重复访问
board[i][j] = ''
res = dfs(i + 1, j, k + 1) or dfs(i - 1, j, k + 1) or dfs(i, j + 1, k + 1) or dfs(i, j - 1, k + 1)
#将 board[i][j] 元素还原至初始值,即 word[k]
board[i][j] = word[k]
return res
for i in range(len(board)):
for j in range(len(board[0])):
if dfs(i, j, 0): return True
return False
2、顺时针打印矩阵
class Solution:
def printMatrix(self , matrix: List[List[int]]) -> List[int]:
# write code here
if not matrix or not matrix[0]:
return []
ans = []
#左、右、上、下
left,right,top,bottom = 0,len(matrix[0])-1,0,len(matrix)-1
while left<=right and top<=bottom:
#从左到右遍历(行是top,列是left-〉right)
for col in range(left,right+1):
ans.append(matrix[top][col])
#从上到下遍历(列是right,行是top+1-〉buttom)
for row in range(top+1,bottom+1):
ans.append(matrix[row][right])
if left < right and top < bottom: #左到右,右到左不能是同一行
#从右到左遍历 (行是bottom,列是right-1-〉left+1)
for col in range(right-1,left,-1):
ans.append(matrix[bottom][col])
#从下到上遍历 (列是left,行是buttom-〉top+1)
for row in range(bottom,top,-1):
ans.append(matrix[row][left])
#left和top分别增加1,将right和bottom分别减少1,进入下一层继续遍历,直到遍历完所有元素为止
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
return ans
3、 把字符串转换成整数(done)
class Solution:
def StrToInt(self , s: str) -> int:
# write code here
s = s.strip() # 删除首尾空格
if not s: return 0 # 字符串为空则直接返回
res, i, sign = 0, 1, 1 #结果、起始位置、符号位
int_max, int_min, bndry = 2 ** 31 - 1, -2 ** 31, 2 ** 31 // 10
if s[0] == '-':
sign = -1 # 保存负号
elif s[0] != '+':
i = 0 # 若无符号位,则需从 i = 0 开始数字拼接
for c in s[i:]:
if not '0' <= c <= '9' :
break # 遇到非数字的字符则跳出
if res > bndry or res == bndry and c > '7':
return int_max if sign == 1 else int_min # 数字越界处理
res = 10 * res + ord(c) - ord('0') # 数字拼接
return sign * res
4、 不用加减乘除做加法(done)
剑指 Offer 65. 不用加减乘除做加法
Python,Java 等语言中的数字都是以 补码 形式存储的。但 Python 没有 int , long 等不同长度变量,即在编程时无变量位数的概念。
获取负数的补码: 需要将数字与十六进制数 0xffffffff 相与。可理解为舍去此数字 32 位以上的数字(将 32 位以上都变为 00 ),从无限长度变为一个 32 位整数。
返回前数字还原: 若补码 aa 为负数( 0x7fffffff 是最大的正数的补码 ),需执行 ~(a ^ x) 操作,将补码还原至 Python 的存储格式。 a ^ x 运算将 1 至 32 位按位取反; ~ 运算是将整个数字取反;因此, ~(a ^ x) 是将 32 位以上的位取反,1 至 32 位不变。
class Solution:
def Add(self , num1: int, num2: int) -> int:
# write code here
x = 0xffffffff
num1, num2 = num1 & x, num2 & x
#循环求 n 和 c ,直至进位c=0 ;此时 s=n ,返回n 即可
while num2 != 0:
#无进位和 与 异或运算 规律相同,进位 和 与运算 规律相同(并需左移一位)
num1, num2 = (num1 ^ num2), (num1 & num2) << 1 & x
return num1 if num1 <= 0x7fffffff else ~(num1 ^ x)
5、1~n 整数中 1 出现的次数(……hard done)
class Solution:
def NumberOf1Between1AndN_Solution(self , n: int) -> int:
# write code here
l = [str(i) for i in range(1,n+1)]
s = ''.join(l)
count = 0
for i in s:
if i== '1':
count += 1
return count
6、把数组排成最小的数(done)
class Solution:
def PrintMinNumber(self , numbers: List[int]) -> str:
# write code here
nums = list(map(str,numbers))
for x in range(len(nums)):
for y in range(x+1,len(nums)):
#字符串相加
if nums[x] + nums[y] > nums[y] + nums[x]:
nums[x],nums[y] = nums[y], nums[x]
return ''.join(nums)
7、和为s的连续正数序列(done)
class Solution:
def findContinuousSequence(self, target: int) -> List[List[int]]:
l,r = 1,2
res = []
while r <= target//2 +1:
a = sum(list(range(l,r+1)))
if a == target:
res.append(list(range(l,r+1)))
l += 1
elif a < target:
r += 1
else:
l += 1
return res
8、约瑟夫环
class Solution:
def lastRemaining(self, n: int, m: int) -> int:
f = 0
for i in range(2,n+1):
f = (m+f) % i
return f