1 class Solution: 2 def minSetSize(self, arr: 'List[int]') -> int: 3 m = len(arr) 4 dic = {} 5 for i in range(m): 6 if arr[i] in dic: 7 dic[arr[i]] += 1 8 else: 9 dic[arr[i]] = 1 10 l = sorted(dic.items(),key=lambda d:(-d[1])) 11 count,target,size = 0,m // 2,0 12 for x in range(len(l)): 13 if count >= target: 14 return size 15 else: 16 size += 1 17 count += l[x][1] 18 return size
算法思想:贪心。
按照出现频率从高到低排序,优先将出现次数多的数字加入到被去除的集合中。