5329数组大小减半

题目:给你一个整数数组 arr。你可以从中选出一个整数集合,并删除这些整数在数组中的每次出现。返回 至少 能删除数组中的一半整数的整数集合的最小大小。

来源:https://leetcode-cn.com/problems/reduce-array-size-to-the-half/

法一:自己的代码

思路:利用贪心算法,先用defaultdict统计出每个元素出现的次数,再由高到底排序,把出现次数逐个求和,一旦大于等于一半,返回结果

from typing import List
from collections import defaultdict
class Solution:
    def minSetSize(self, arr: List[int]) -> int:
        d = defaultdict(int)
        size = int(len(arr)/2)
        for i in arr:
            d[i] += 1
        ans = 0
        s = 0
        k = sorted(d.values())
        k.reverse()
        for i in k:
            s += i
            ans += 1
            if s >= size:
                return ans
if __name__ == '__main__':
    duixiang = Solution()
    # a = duixiang.minSetSize(arr = [3,3,3,3,5,5,5,2,2,7])
    a = duixiang.minSetSize(arr = [1,9])
    print(a)
View Code

法二:别人代码

思路:同上,学会Counter的用法,以及a.sort(reverse=True),还有合理选择while和for,有时用while更优雅。

import collections
from typing import List
class Solution:
    def minSetSize(self, arr: List[int]) -> int:
        # key是数组里的元素,values是出现频率
        cnt = collections.Counter(arr)
        print(cnt)
        l = len(arr)
        x = list(cnt.values())
        # 学会这里的写法,实现了由大到小排序
        x.sort(reverse=True)
        ans = 0
        c = 0
        while c < l / 2:
            c += x[ans]
            ans += 1
        return ans
if __name__ == '__main__':
    duixiang = Solution()
    a = duixiang.minSetSize(arr = [3,3,3,3,5,5,5,2,2,7])
    # a = duixiang.minSetSize(arr = [1,9])
    print(a)
View Code
原文地址:https://www.cnblogs.com/xxswkl/p/12253044.html