Leetcode 1338. Reduce Array Size to The Half

2021-07-08 16:23:08 浏览数 (1)

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

1. Description

2. Solution

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

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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/

0 人点赞