1. 程式人生 > 實用技巧 >1338. Reduce Array Size to The Half

1338. Reduce Array Size to The Half

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,然後再維護一個key是出現次數f,value是出現次數的次數。比如[2,2,3,3,4]->count[0, 2, 2, 1]->f[1, 2, 0, 0]

然後對於f,index從大到小去遍歷,長度減小index步,直到長度小於等於一半。

class Solution(object):
    def minSetSize(self, arr):
        """
        :type arr: List[int]
        :rtype: int
        """
        count = {}
        for value in arr:
            if value in count:
                count[value] += 1
            else:
                count[value] 
= 1 f = [0] * (len(arr) + 1) for key,value in count.items(): f[value] += 1 ans = 0 step = len(arr) k = step // 2 print(count, f) for i in range(len(arr), 0, -1): if f[i] != 0: while f[i] > 0: f[i]
-= 1 step -= i ans += 1 if step <= k: return ans return ans