leetcode-1338 Reduce Array Size to The Half
阿新 • • 發佈:2020-11-01
題目:
Given an arrayarr
. You can choose a set of integers and remove all the occurrences of these integers in the array.
Returnthe minimum size of the setso thatat leasthalf of the integers of the array are removed.
樣例:
限制:
個人思路:
先一個字典統計所有的字元出現的個數,然後按照從大到小的順序進行排序,然後count--,當count * 2 <= len(arr)時結束,統計此時減去的數字的個數即可。
程式碼:
1 class Solution: 2 def minSetSize(self, arr: List[int]) -> int: 3 n = len(arr) 4 count = {} 5 for i in arr: 6 if count. __contains__(str(i)): 7 count[str(i)] +=1 8 else: 9 count[str(i)] = 1 10 count = sorted(count.items(), key=lambdax:x[1], reverse=True) 11 num = 0 12 for i in count: 13 n -= i[1] 14 num += 1 15 if n * 2 <= len(arr): 16 break 17 return num 18