Weekly Contest 318
Weekly Contest 318
Problem A
Apply Operations to an Array
思路
按照题意模拟即可
代码
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
l = len(nums)
for i in range(0,l-1):
if nums[i]==nums[i+1]:
nums[i]*=2
nums[i+1] =0
ans = []
for i in range(l):
if nums[i]!=0:
ans.append(nums[i])
# print(ans,l)
d = l-len(ans)
for i in range(len(ans),l):
ans.append(0)
return ans
Problem B
Maximum Sum of Distinct Subarrays With Length K
思路
滑动窗口,r一直加,l当出现重复或者是找到一个可行解时加。是一个MAP存储位置,方便找到下一个l的位置,在跳的过程别忘了更新SUM
代码
class Solution:
def maximumSubarraySum(self, nums: List[int], k: int) -> int:
ans = 0
i,j,n = 0,0,len(nums)
M = {}
SUM = 0
if n<k:
return 0
if k == 1:
return max(nums)
l,r = 0,0
while r<n:
t = nums[r]
SUM+=nums[r]
if (t not in M.keys() or M[t]==-1):
if r-l+1==k:
ans = max(ans,SUM)
SUM-=nums[l]
M[nums[l]]=-1
l+=1
else:
site = M[t]
while l<=site:
M[nums[l]] =-1
SUM-=nums[l]
l+=1
M[nums[r]] = r
r+=1
return ans
Problem C
Total Cost to Hire K Workers
思路
本质上来说就是用优先队列来实现$log(N)$的查找(Python用的最小堆),但是写起来BUG有点多,调起来很麻烦,赛后才过的。
代码
class Solution:
def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
n = len(costs)
# print(n)
if candidates>=n:
costs.sort()
return sum(costs[:k])
L = []
# print(1)
for i in range(candidates):
l,r = i,n-1-i
if r>=l:
L.append([costs[l],l,1])
if r!=l:
L.append([costs[r],r,2])
t = (len(L)+1)//2
l,r = t-1,n-t
heapq.heapify(L)
ans = 0
for i in range(k):
v,s,x = heapq.heappop(L)
ans+=v
if r-l<=1:
continue
if x == 1:
heapq.heappush(L,[costs[l+1],l+1,1])
l+=1
else:
heapq.heappush(L,[costs[r-1],r-1,2])
r-=1
return ans
Problem D
Height of Binary Tree After Subtree Removal Queries
思路
思路很简单,就是两次DFS。一次dfs确定深度,一次得到结果,在第二次DFS时做的是得到除当前路径之外的最大深度,也就是答案。感觉这个思路蛮巧妙的
代码
class Solution:
def treeQueries(self, root: Optional[TreeNode], queries: List[int]) -> List[int]:
height = defaultdict(int) # 每棵子树的高度
def get_height(node: Optional[TreeNode]) -> int:
if node is None: return 0
height[node] = 1 + max(get_height(node.left), get_height(node.right))
return height[node]
get_height(root)
res = [0] * (len(height) + 1) # 每个节点的答案
def dfs(node: Optional[TreeNode], depth: int, rest_h: int) -> None:
if node is None: return
depth += 1
res[node.val] = rest_h
dfs(node.left, depth, max(rest_h, depth + height[node.right]))
dfs(node.right, depth, max(rest_h, depth + height[node.left]))
dfs(root, -1, 0)
for i, q in enumerate(queries):
queries[i] = res[q]
return queries
总结
出了3题,但是感觉蛮冗余的,最后一题的思路蛮巧妙地,可惜没想出来。
过往不恋 未来不迎 当下不负