LeetCode #1560. Most Visited Sector in a Circular Track
题目
1560. Most Visited Sector in a Circular Track
解题方法
先设置一个字典用来计数,然后遍历rounds数组,start设置为起始位置,end设置为当前的结束位置,循环内部做循环当start!=end时增加start的值并计数。计数部分结束后找到字典中的最大值,并且统计最大值个数,最后排序。
时间复杂度:O(nlogn)
空间复杂度:O(n)
代码
class Solution:
def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
dic = {}
for i in range(1, n+1): dic[i] = 0
start = rounds[0]
dic[start] = 1
for i in range(1, len(rounds)):
end = rounds[i]
while start != end:
start = (start + 1) % n
if not start:
start = n
dic[start] += 1
maxvisitcount = max(dic.values())
rat = []
for key in dic.keys():
if dic[key] == maxvisitcount:
rat.append(key)
rat.sort()
return rat