Leetcode 1338. Reduce Array Size to The Half

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

1. Description

Reduce Array Size to The Half

2. Solution

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

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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/
如果有收获,可以请我喝杯咖啡!