Skip to content

1338. Reduce Array Size to The Half 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int minSetSize(vector<int>& arr) {
    const int n = arr.size();
    int sum = 0;
    unordered_map<int, int> map;
    vector<pair<int, int>> count;

    for (const int a : arr)
      ++map[a];

    for (const auto& [a, freq] : map)
      count.push_back(make_pair(a, freq));

    ranges::sort(count, [](const pair<int, int>& a, const pair<int, int>& b) {
      return a.second > b.second;
    });

    for (int i = 0; i < count.size(); ++i) {
      sum += count[i].second;
      if (sum >= n / 2)
        return i + 1;
    }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
  public int minSetSize(int[] arr) {
    final int n = arr.length;
    int sum = 0;
    Map<Integer, Integer> map = new HashMap<>();

    for (final int a : arr)
      map.merge(a, 1, Integer::sum);

    int[][] count = new int[map.size()][2];
    int i = 0;

    for (final int key : map.keySet()) {
      count[i][0] = key;
      count[i++][1] = map.get(key);
    }

    Arrays.sort(count, (c1, c2) -> c2[1] - c1[1]);

    for (i = 0; i < count.length; ++i) {
      sum += count[i][1];
      if (sum >= n / 2)
        return i + 1;
    }

    throw new IllegalArgumentException();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def minSetSize(self, arr: List[int]) -> int:
    n = len(arr)

    count = collections.Counter(arr).most_common()
    count.sort(key=lambda c: -c[1])

    summ = 0
    for i, c in enumerate(count):
      summ += c[1]
      if summ >= n // 2:
        return i + 1