题目链接
2808. 使循环数组所有元素相等的最少秒数 - 力扣(LeetCode)
解题思路
我们首先用哈希表,统计nums中相同的数出现的位置,mp[x]表示x所出现的位置。然后我们研究,使得数组全部变成x所需要的时间,这个时间取决于nums中,相邻x的最大距离。我们一次枚举所有相邻(包括头尾)x的索引值,找到最大的距离。最大距离除以二并向下取整,就是使得数组全部变成x所需要得时间。
最后我们对所有nums中得数都找到所需得时间,返回其中得最小值即可。
解题代码
class Solution:
def minimumSeconds(self, nums: List[int]) -> int:
mp = defaultdict(list)
res = n = len(nums)
for i,a in enumerate(nums):
mp[a].append(i)
for pos in mp.values():
mx = pos[0] + n - pos[-1]
for i in range(len(pos)):
mx = max(mx,pos[i] - pos[i - 1])
res = min(res,mx//2)
return res