📅  最后修改于: 2023-12-03 14:49:36.129000             🧑  作者: Mango
给定一个非空整数数组,我们可以移除其中一个元素,使得剩下的元素频率相等。找到使此条件成立的最小移除次数。
为了使剩余数组元素频率相等,我们需要满足以下条件:
因此,我们可以采取以下步骤来解决这个问题:
代码实现:
def min_remove(nums):
freq = {}
for num in nums:
freq[num] = freq.get(num, 0) + 1
counts = list(freq.values())
max_count = max(counts)
min_count = min(counts)
if max_count == len(nums) // 2:
return len(nums) - max_count
elif min_count == len(nums) // 2:
return len(nums) - min_count
else:
for i in range(2, len(nums), 2):
if sum(counts[:i]) == sum(counts)-sum(counts[:i]):
return len(nums)-sum(counts[:i])
return -1