使用Python查找环形轨道中最多被访问的区域的程序
假设我们有一个数字n和一个名为rounds的数组。我们有一个由1到n标记的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只被访问1次。
为了解决这个问题,我们需要遵循以下步骤−
- d := 一个新映射
-
对于j从1到n,执行
- d [j] := 0
- d [rounds [0]] := 1
-
对于i从1到rounds的大小-1,执行
- 如果rounds [i]> rounds [i-1],则
- 对于j从rounds [i-1] + 1到rounds [i] + 1,执行
-
d [j] := d [j] +1
-
否则,
- 对于j从rounds [i-1] + 1到n,执行
-
d [j] := d [j] +1
-
对于j从1到rounds [i],执行
-
d [j] := d [j] +1
- 如果rounds [i]> rounds [i-1],则
-
curr := d [rounds [0]]
-
out := [rounds [0]]
-
对于i从1到n,执行
- 如果i与rounds [0]不相同,则
- 如果d [i]> curr,则
-
curr := d [i]
-
out := [i]
-
否则,当d [i]等于curr时,
-
将i附加到out中
- 如果i与rounds [0]不相同,则
-
排序后返回out
示例(Python)
让我们看一下以下实现以获得更好的理解−