使用 Python 编写程序,在删除 K 个元素后找出最少数量的非重复整数
pythonserver side programmingprogramming更新于 2025/5/26 19:56:17
假设我们有一个名为 nums 的数组,其中只存储整数。如果我们有一个数字 k。我们必须找到在删除恰好 k 个元素后最少数量的唯一元素。
因此,如果输入为 nums = [5,4,2,2,4,4,3],k = 3,则输出将为 2,因为如果我们删除 5 和 3,以及任意一个 2 或任意一个 4,则只剩下 2 和 4。
为了解决这个问题,我们将遵循以下步骤 −
dictionary:= a new map
对于 nums 中的每个数字,执行
如果 num 不在字典中,则
dictionary[num]:= 1
否则,
dictionary[num] := dictionary[num] + 1
count:= 字典大小
对于字典中所有值排序后的每个频率,执行
k := k - 频率
如果 k < 0,则
返回 count
否则,
count := count - 1
返回 count
让我们看看下面的实现以便更好地理解 −
示例
def solve(nums, k):
dictionary={}
for num in nums:
if num not in dictionary:
dictionary[num]=1
else:
dictionary[num]+=1
count=len(dictionary)
for frequency in sorted(dictionary.values()):
k-=frequency
if(k<0):
return count
else:
count-=1
return count
nums = [5,4,2,2,4,4,3]
k = 3
print(solve(nums, k))
输入
[5,4,2,2,4,4,3], 3
输出
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

