给出题目一的试题链接如下:
这一题没啥好说的,搞个counter统计一下就行了。
给出python代码实现如下:
class Solution:
def areOccurrencesEqual(self, s: str) -> bool:
cnt = list(Counter(s).values())
return all(x == cnt[0] for x in cnt)
提交代码评测得到:耗时32ms,占用内存14.3MB。
给出题目二的试题链接如下:
这一题的思路也还好,我们首先将人员按照到场时间重新排序,然后用两个堆栈分别来记录当前椅子的空余情况已经椅子按照时间被释放的情况。
此后,每当一个人进场时,我们都根据进场时间来释放椅子,然后从空余的椅子列表当中选择最小序列的椅子分配给该客人即可。
当客人序号等于目标序号时,我们就可以直接返回答案了。
给出python代码实现如下:
class Solution:
def smallestChair(self, times: List[List[int]], targetFriend: int) -> int:
n = len(times)
q = []
seats = [i for i in range(n)]
heapq.heapify(seats)
times = sorted([x, y, i] for i, (x, y) in enumerate(times))
for x, y, i in times:
while q != [] and q[0][0] <= x:
_, s = heapq.heappop(q)
heapq.heappush(seats, s)
s = heapq.heappop(seats)
if i == targetFriend:
return s
heapq.heappush(q, (y, s))
return -1
提交代码评测得到:耗时708ms,占用内存19.6MB。
给出题目三的试题链接如下:
这一题思路其实也挺常见的,就是对首尾进行标记,然后最后累计求和,尤其题目中还限定了颜色不会重复出现,因此只要出现了内容的片段就必然不会是重复的,因此我们就可以通过一个标量的值直接来标记当前位置下所有的颜色增减情况。
给出python代码实现如下:
class Solution:
def splitPainting(self, segments: List[List[int]]) -> List[List[int]]:
n = max([x[1] for x in segments])
colors = [[0, 0] for _ in range(n+1)]
for st, ed, c in segments:
colors[st][0] += c
colors[ed][1] += c
pre, mix, res = -1, 0, []
for i, (add, minus) in enumerate(colors):
if add == 0 and minus == 0:
continue
if pre != -1 and mix != 0:
res.append([pre, i, mix])
pre = i
mix = mix + add - minus
return res
提交代码评测得到:耗时1376ms,占用内存39.6MB。
给出题目四的试题链接如下:
这一题就是一道单调队列的问题,不过坑爹的是虽然有思路不过想了半天各种bug,最后看了答案才给出了解答,这里就不多说了,直接给出官方的解答链接吧……
官方解答:队列中可以看到的人数
我们的代码实现如下:
class Solution:
def canSeePersonsCount(self, heights: List[int]) -> List[int]:
n = len(heights)
res = [0 for _ in range(n)]
insight = []
for i in range(n-1, -1, -1):
while insight:
res[i] += 1
if insight[0] <= heights[i]:
insight.pop(0)
else:
break
insight.insert(0, heights[i])
return res
提交代码评测得到:耗时7460ms,占用内存29.8M。