1471. 数组中的 k 个最强值
排序 然后 双指针前后扫
class Solution:
def getStrongest(self, arr: List[int], k: int) -> List[int]:
arr.sort()
num = arr[(len(arr)-1)//2]
re =[]
left,right =0,len(arr)-1
for i in range(k):
if abs(arr[right]-num)>= abs(arr[left] -num):
re.append(arr[right])
right -=1
else :
re.append(arr[left])
left +=1
return re
112. 路径总和
BFS 每个节点重新赋值 做所有父节点值的和 最后到叶子节点时,判断是否等于目标值
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
que = [root]
num = [0,]
while len(que)>0:
now = que[0]
now.val +=num[0]
if now.left:
que.append(now.left)
num.append(now.val)
if now.right:
que.append(now.right)
num.append(now.val)
if not now.left and not now.right and now.val == targetSum:
return True
del que[0],num[0]
return False