使用 Python 编写程序,在圆形跑道中查找访问量最大的扇区
假设我们有一个数字 n 和一个名为 rounds 的数组。我们有一个圆形跑道,它由 n 个不同的扇区组成,标记为 1 到 n。现在假设将在这条跑道上举行一场比赛,比赛由 m 个不同的回合组成。第 i 回合从扇区 rounds[i - 1] 开始,到扇区 rounds[i] 结束。例如,如果第 1 回合从扇区 rounds[0] 开始,到扇区 rounds[1] 结束。因此,我们必须按升序找到访问量最大的扇区。 (轨道号按逆时针方向按扇区号升序排列)
因此,如果输入为 n = 4 rounds = [1,3,1,2],则输出为 [1, 2]

因为比赛从扇区 1 开始。访问的扇区的顺序如下:[1,2,3(第一轮结束),4,1(第二轮结束),2(第三轮结束)]。这里扇区 1 和 2 都被访问了两次,它们是访问次数最多的扇区。并且第 3 区和第 4 区只被访问过一次。
为了解决这个问题,我们将遵循以下步骤 −
d := a new map
对于范围从 1 到 n 的 j,执行
d[j] := 0
d[rounds[0]] := 1
对于范围从 1 到 rounds 大小 - 1 的 i,执行
如果 rounds[i] > rounds[i-1],然后
对于范围为 rounds[i-1]+1 到 rounds[i]+1 的 j,执行
d[j] := d[j] + 1
否则,
对于范围为 rounds[i-1]+1 到 n 的 j,执行
d[j] := d[j] + 1
对于范围为 1 到 rounds[i] 的 j,执行
d[j] := d[j] + 1
curr := d[rounds[0]]
out := [rounds[0]]
对于范围从 1 到 n 的 i,执行
如果 i 与 rounds[0] 不同,则
如果 d[i] > curr,则
curr := d[i]
out := [i]
否则,当 d[i] 与 curr 相同时,则
将 i 附加到 out 中
排序后返回 out
示例 (Python)
让我们看看下面的实现以便更好地理解 −
def solve(n, rounds):
d = {}
for j in range(1,n+1):
d[j] = 0
d[rounds[0]] = 1
for i in range(1, len(rounds)):
if rounds[i] > rounds[i-1]:
for j in range(rounds[i-1]+1, rounds[i]+1):
d[j] += 1
else:
for j in range(rounds[i-1]+1,n+1):
d[j] += 1
for j in range(1,rounds[i]+1):
d[j] += 1
curr = d[rounds[0]]
out = [rounds[0]]
for i in range(1,n+1):
if i != rounds[0]:
if d[i] > curr:
curr = d[i]
out = [i]
elif d[i] == curr:
out = out + [i]
return(sorted(out))
n = 4
rounds = [1,3,1,2]
print(solve(n, rounds))
输入
4, [1,3,1,2]
输出
[1, 2]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

