Leetcode 1338. Reduce Array Size to The Half

Posted SnailTyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1338. Reduce Array Size to The Half相关的知识,希望对你有一定的参考价值。

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Reduce Array Size to The Half

2. Solution

**解析:**对数组中的元素个数进行统计,并按从大到小排列,一次移除一个元素,直至剩余元素个数小于等于移除的元素个数。

  • Version 1
class Solution:
    def minSetSize(self, arr: List[int]) -> int:
        stat = {}
        n = len(arr)
        for num in arr:
            stat[num] = stat.get(num, 0) + 1

        values = sorted(stat.values(), reverse=True)
        count = 0
        size = 0
        for v in values:
            size += 1
            count += v
            thres = count * 2
            if thres >= n:
                break
        return size
  • Version 2
class Solution:
    def minSetSize(self, arr: List[int]) -> int:
        stat = Counter(arr)
        n = len(arr)
        
        values = sorted(stat.values(), reverse=True)
        count = 0
        size = 0
        for v in values:
            size += 1
            count += v
            thres = count * 2
            if thres >= n:
                break
        return size

Reference

  1. https://leetcode.com/problems/reduce-array-size-to-the-half/

以上是关于Leetcode 1338. Reduce Array Size to The Half的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 1338. Reduce Array Size to The Half

1338. Reduce Array Size to The Half

1338.数组大小减半

JS数组reduce()方法

手写reduce()

reduce()累加器