5637. 判断字符串的两半是否相似
class Solution:
def halvesAreAlike(self, s: str) -> bool:
score = ('a','e','i','o','u','A','E','I','O','U')
a = s[:len(s)//2]
b = s[len(s)//2:]
sa = 0
for ch in a:
if ch in score:
sa += 1
sb = 0
for ch in b:
if ch in score:
sb += 1
return sa == sb
5638. 吃苹果的最大数目
emmm。。。一开始暴力模拟直接TLE了
然后改变了一下策略,用ind来记录当前天数,然后每次碰到苹果的时候,判断它生长出来的天数和保质期还有当天天数的关系,没有腐烂则吃掉它
想当然的选择了最先生长出来的苹果吃掉,提交上去WA了,意识到这个策略不对,应该尽可能的选取即将要腐烂的苹果吃掉,而不是最先生长出来的苹果
既然要统计即将腐烂的苹果,想当然的使用优先队列,python里面的用小根堆来实现(不过python的heapq用起来真的不太顺手。。。看来有必要用c++刷题)
下面是题解:
对于apples[i],它的保质期为days[i],那么这样的apples[i]最多存在days[i]天,我们用一个额外的变量ind
统计天数,如果apples[i]的days[i]<=ind,那么视为这个apple已经腐烂了
那么我们如何更好的判断一个苹果是否腐烂,注意到days[i]是它的保质期,如果这个苹果在第ind
天长出来,那么它最多能保持到第ind+days[i]
天,我们将这个信息入队,然后判断这个信息即可
然后我们贪心的策略就是,从一堆苹果中尽可能地选取快要腐烂的苹果作为当前的选择即可
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
que = []
heapq.heapify(que)
ans = 0
ind = 1
for a,d in zip(apples,days):
# 小根堆,注意是腐烂日期记录在前
heapq.heappush(que, [d + ind, a])
while que != []:
top = heapq.heappop(que)
if top[1] == 0 or top[0] <= ind:
continue
# 吃掉一个苹果
top[1] -= 1
ans += 1
heapq.heappush(que, top)
# 吃掉后记得break
break
# 天数往后移
ind += 1
while que != []:
top = heapq.heappop(que)
if top[1] == 0 or top[0] <= ind:
continue
# 吃掉一个苹果
top[1] -= 1
ans += 1
heapq.heappush(que, top)
# 天数往后移
ind += 1
return ans
注意到第二个循环,我们已经选择了一个即将腐烂的apple,那么我们没必要只吃1个再放回,而是尽可能的吃掉这些即将腐烂的apple,为什么说是尽可能呢?假设这些苹果有5个,它还剩下2天腐烂,那么我们只能吃掉2个,假设这些苹果有2个,它还剩下5天腐烂,那么我们能吃掉2个,显然吃掉的苹果个数是两个值之间的最小值,下面是优化后的代码
class Solution:
def eatenApples(self, apples: List[int], days: List[int]) -> int:
que = []
heapq.heapify(que)
ans = 0
ind = 1
for a,d in zip(apples,days):
# 小根堆,注意是腐烂日期记录在前
heapq.heappush(que, [d + ind, a])
while que != []:
top = heapq.heappop(que)
if top[1] == 0 or top[0] <= ind:
continue
# 吃掉一个苹果
top[1] -= 1
ans += 1
heapq.heappush(que, top)
# 吃掉后记得break
break
# 天数往后移
ind += 1
while que != []:
top = heapq.heappop(que)
if top[1] == 0 or top[0] <= ind:
continue
eats = min(top[1],top[0] - ind)
ans += eats
# 天数往后移
ind += eats
return ans
5210. 球会落何处
这题是没来得及写的,当场写一下
还是模拟题
class Solution:
def findBall(self, grid: List[List[int]]) -> List[int]:
m, n = len(grid), len(grid[0])
ans = [0 for _ in range(n)]
def dfs(x,y):
# print(x,y)
# 卡在边界
if y < 0 or y>=n:
return -1
# 没有卡在边界,同时滚动到底部
if x >= m:
return y
# 向右下角走
if grid[x][y] == 1:
# 检查是否会构成V
if y < n - 1 and grid[x][y+1] == -1:
return -1
return dfs(x+1,y+1)
else:
if y>0 and grid[x][y-1] == 1:
return -1
return dfs(x+1,y-1)
for i in range(n):
ans[i] = dfs(0,i)
return ans
暴力dfs过了。。。讲道理第二题比第三题难想多了
5640. 与数组中元素的最大异或值
不会
经历
第一次报名。。然而睡到11点半才想起来自己报名了,赶紧爬起来做题
第一题手速题
卡在第二题了,说实话第二题不难,但是基础不好的人(指我)做起来会很吃力
第三题看了一眼,感觉也是能做的,模拟,但是没时间做了
第四题完全没看,出来看了评论好像是字典树,emmm没听说过