前言
继续leetcode刷题生涯
这里记录的都是笔者觉得有点意思的做法
参考了好几位大佬的题解,感谢各位大佬
1103. 分糖果 II
class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
res = [0] * num_people
num = 1
while candies > 0:
idx = (num-1) % num_people
if candies >= num:
res[idx] += num
candies -= num
num += 1
else:
res[idx] += candies
candies = 0
return res
1104. 二叉树寻路
class Solution:
def pathInZigZagTree(self, label: int) -> List[int]:
if label == 1: return [1]
res = [label]
while label > 1:
level = int(math.log2(label))
level_start = 2 ** level
remain = (label - level_start) // 2
label = level_start - 1 - remain
res.append(label)
return res[::-1]
1105. 填充书架
class Solution:
def minHeightShelves(self, books: List[List[int]], shelf_width: int) -> int:
n = len(books)
dp = [1000000] * (n + 1)
dp[0] = 0
for i in range(1, n + 1):
tmp_width, j, h = 0, i, 0
while j > 0:
tmp_width += books[j - 1][0]
if tmp_width > shelf_width:
break
h = max(h, books[j - 1][1])
dp[i] = min(dp[i], dp[j - 1] + h)
j -= 1
return dp[-1]
1106. 解析布尔表达式
class Solution:
def parseBoolExpr(self, expression: str) -> bool:
arr=[]
for x in expression: # 倒序记录exp,除掉‘,’,将tf换成布尔值
if x==',':
continue
elif x=='t':
arr.append(True)
elif x=='f':
arr.append(False)
else:
arr.append(x)
b=[] # b用于记录‘)’和将用于计算和计算完毕的布尔变量
while len(arr)>0 or len(b)!=1: # 当arr=None且b只有一个变量时跳出循环
x=arr.pop()
if x=='(': # 倒序遍历exp,遇到‘(’,则下一个必定是运算符op
op=arr.pop() # 运算符op从arr出栈,而布尔变量从b出栈
x=b.pop()
if op=='!':
res=not x
x=b.pop() # 由于‘!’取非后面必定只有一个布尔变量,所以要把多余的‘)’顶出栈b
if op=='&':
res=True # 真并x=x(True不会改变x的布尔值)
while x!= ')': # 当op为并、或时需要连续出栈操作
res=res and x
x=b.pop()
if op=='|':
res=False # 假或x=x(同上)
while x!= ')':
res=res or x
x=b.pop()
x=res # res覆盖x,因为x覆盖前=运算结束后多余的‘)’符号,要除掉
b.append(x) # 将运算结果或者还没遇到op的布尔变量和分隔符‘)’入栈b
return b.pop() # 当栈b只剩一个变量时,就是最终答案
1108. IP 地址无效化
class Solution:
def defangIPaddr(self, address: str) -> str:
return address.replace(".","[.]")
1109. 航班预订统计
class Solution:
def corpFlightBookings(self, bookings: List[List[int]], n: int) -> List[int]:
res = [0] * (n+1)
for i, j, k in bookings:
res[i-1] += k
res[j] -= k
for i in range(1, n+1):
res[i] += res[i-1]
return res[:n]
1110. 删点成林
class Solution:
def delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
d = set(to_delete)
res = [root] if root and root.val not in d else []
def dfs(node, p, arrow):
if not node: return
dfs(node.left, node, 'left')
dfs(node.right, node, 'right')
if node.val in to_delete:
if node.left: res.append(node.left)
if node.right: res.append(node.right)
if arrow == "left":
p.left = None
elif arrow == "right":
p.right = None
dfs(root, None, None)
return res