LeetCode 1338. Reduce Array Size to The Half
考点 | 难度 |
---|---|
Greedy | Easy |
题目
You are given an integer array arr. You can choose a set of integers and remove all the occurrences of these integers in the array.
Return the minimum size of the set so that at least half of the integers of the array are removed.
思路
用hashmap记录frequency,从大到小删数字直到删完大于一半
答案
class Solution:
def minSetSize(self, arr):
cnt = Counter(arr)
frequencies = list(cnt.values())
frequencies.sort()
ans, removed, half = 0, 0, len(arr) // 2
while removed < half:
ans += 1
removed += frequencies.pop()
return ans