56. 合并区间
python
class Solution:
def merge(self, intervals: List[List[int]]) -> List[List[int]]:
intervals.sort(key=lambda p: p[0]) # 按照左端点从小到大排序
ans = []
for p in intervals:
if ans and p[0] <= ans[-1][1]: # 可以合并
ans[-1][1] = max(ans[-1][1], p[1]) # 更新右端点最大值
else: # 不相交,无法合并
ans.append(p) # 新的合并区间
return ans
738.单调递增的数字
python
class Solution:
def monotoneIncreasingDigits(self, N: int) -> int:
nums = list(str(N))
length = len(nums)
begin = 0
# N 是否符合条件
is_result = True
max_num = float('-inf')
# 从前往后观察
for i in range(1, length):
num = int(nums[i])
pre_num = int(nums[i - 1])
# 记录最大值
if pre_num > max_num:
begin = i - 1
max_num = pre_num
if pre_num > num:
is_result = False
break
# 如果 N 本身符合条件,直接返回 N
if is_result:
return N
# begin 位置减去 1,后面全部替换为 9
nums[begin] = str(int(nums[begin]) - 1)
for i in range(begin + 1, length):
nums[i] = '9'
return int("".join(nums))
968.监控二叉树
python
class Solution:
def minCameraCover(self, root: Optional[TreeNode]) -> int:
def dfs(node):
if node is None:
return inf, 0, 0 # 空节点不能安装摄像头,也无需被监控到
l_choose, l_by_fa, l_by_children = dfs(node.left)
r_choose, r_by_fa, r_by_children = dfs(node.right)
choose = min(l_choose, l_by_fa) + min(r_choose, r_by_fa) + 1
by_fa = min(l_choose, l_by_children) + min(r_choose, r_by_children)
by_children = min(l_choose + r_by_children, l_by_children + r_choose, l_choose + r_choose)
return choose, by_fa, by_children
choose, _, by_children = dfs(root) # 根节点没有父节点
return min(choose, by_children)