这周的周赛比较简单,前面两道简单题,第三道题中等题,第四道题hard题
写出来了3道题,最后一道不会
模拟:简单题
这道题很容易想复杂,用dp或者dfs来做,反而把简单问题复杂化了。
class Solution:
def answerQueries(self, nums: List[int], queries: List[int]) -> List[int]:
nums.sort()
res = [0 for _ in range(len(queries))]
for i in range(len(queries)):
cur_sum = 0
for j in range(len(nums)):
if cur_sum + nums[j] <= queries[i]:
cur_sum += nums[j]
res[i] += 1
else: break
return res
普通stack:简单题
class Solution:
def removeStars(self, s: str) -> str:
stack = []
for i in range(len(s)):
# if i == 0: return ''
if s[i] != '*':
stack.append(s[i])
else:
if stack:
stack.pop()
return ''.join(stack)
模拟题:中等题
用个hash表来记录每种垃圾的出现次数,来判断垃圾车还需不需要继续开往下一个地点。
class Solution:
def garbageCollection(self, garbage: List[str], travel: List[int]) -> int:
mapp = defaultdict(int)
for string in garbage:
for j in range(len(string)):
if string[j] == 'M':
mapp['M'] += 1
elif string[j] == 'P':
mapp['P'] += 1
elif string[j] == 'G':
mapp['G'] += 1
def son(mapp, key):
res = 0
i = 0
while mapp[key] != 0 and i < len(garbage):
if 0 < i < len(garbage):
res += travel[i-1]
for j in range(len(garbage[i])):
if garbage[i][j] == key:
res += 1
mapp[key] -= 1
i += 1
return res
res = 0
g = ['M', 'P', 'G']
for i in range(len(g)):
res += son(mapp, g[i])
return res
hard题,拓扑排序,没写出来