1338. Reduce Array Size to The Half
Posted whatyouthink
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1338. Reduce Array Size to The Half相关的知识,希望对你有一定的参考价值。
Given an 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.
给一个数组,最少去掉多少个相同的数字,可以使得数组长度小于等于原始长度的一半。
先统计每个元素出现的次数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
以上是关于1338. Reduce Array Size to The Half的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 1338. Reduce Array Size to The Half 数组大小减半
Leetcode 1338. Reduce Array Size to The Half